Ad
How To Fix Lost Time In Date After Converting?
I want to test my DateUtil
class and I got error - after converting my Date
to String
and back to Date I lost about 900 seconds.
This is my code:
fun convertStringToDate() {
// here I get current Date
val currentDate = Date() // 1514285741928
// see apiDateFormatter declaration below this code
val dateStr = apiDateFormatter.format(currentDate) // Tue, 26 Dec 2017 12:55:41 GMT+02:00
// see convertStringToDate() method declaration below this code
val convertedDate = DateUtil.convertStringToDate(dateStr) // 1514285741000
assertEquals(currentDate == convertedDate, true)
}
apiDateFormatter
val DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"
val apiDateFormatter = SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH)
DateUtil.convertStringToDate(dateStr)
fun convertStringToDate(dateStr: String): Date {
return apiDateFormatter.parse(dateStr)
}
The difference between currentDate
and convertedDate
is about 900 seconds.
Why and how fix it?
Ad
Answer
The two UNIX epoch timestamps you have are actually in milliseconds, not seconds. Here are the two values:
1514285741928 - before
1514285741000 - after
The difference between the two timestamps in 928 milliseconds. All that has happened is that the millisecond component was truncated off. The truncation happened when you applied a seconds-level precision date mask at this line:
val dateStr = apiDateFormatter.format(currentDate)
To get around this problem, you can try changing your SimpleDateFormat
mask to include milliseconds:
val DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss.SSS zzz"
// ^^^ add this
val apiDateFormatter = SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH)
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad