Belphegor
Belphegor

Reputation: 1843

Why is the time incorrect when I convert from milliseconds to local time in Android?

    fun format(input: Long, outputFormat: String = "yyyy-MM-dd'T'HH:mm:ss", locale: Locale = Locale.US): String {
        SimpleDateFormat(outputFormat, locale).apply {
        return format(Date(input))
    }

I have the following method above, when I enter the following command:

println(format(1596095340000))

I am expecting to get

2020-07-29T17:49:00

however I end up getting this instead

2020-07-30T07:49:00

Do I have to manually do the offset myself, and if I do how would I do that? I thought that this type of offset would be handled automatically?

I've also adapted answer from another SO post at Converting from Milliseconds to UTC Time in Java and results were different but still not what I expected:

    val sdf = SimpleDateFormat()
    sdf.timeZone = TimeZone.getTimeZone("PST")
    println(sdf.format(Date(1596095340000)))

7/30/20 12:49 AM

Upvotes: 1

Views: 314

Answers (1)

Joni
Joni

Reputation: 111339

The time stamp 1596095340000 corresponds to the instant 2020-07-30T07:49:00 UTC - you can verify this at any online date/time conversion site.

By default, SimpleDateFormat uses the system time zone. From your output, it looks like the system time zone coincides with UTC.

To get the result you expect 2020-07-29T17:49:00 you would need a time zone with a 14 hour offset:

var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
sdf.setTimeZone(TimeZone.getTimeZone("GMT-1400"))
sdf.format(new Date(1596095340000L)) // "2020-07-29T17:49:00"

No place in the world has a 14 hour time zone offset. Either your time stamp is wrong, or the result you expect is wrong. For example, if you got the date wrong, your expected time zone might be Australia/Sydney:

sdf.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"))
sdf.format(new Date(1596095340000L)) // "2020-07-30T17:49:00"

Upvotes: 1

Related Questions