Ad

How To Fix Lost Time In Date After Converting?

- 1 answer

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
Ad