javakotlindateepochdatetime-conversion

Java/Kotlin String Date to milliseconds conversion


I am trying to figure out how the https://www.epochconverter.com/ website converts a String date to milliseconds and then replicate the same logic in Java/Kotlin code. But I am unable to come up with an equivalent Java/Kotlin code.

For example, for the date "1979/12/31 23:30:00" is converted to 315552600000 milliseconds by https://www.epochconverter.com/ enter image description here

but my below kotlin code outputs 315531000000 instead of 315552600000.

import java.text.SimpleDateFormat
import java.time.*
import java.time.format.DateTimeFormatter
import java.util.*


fun main(){ 
        
    val startTime = "1979/12/31 23:30:00"
    val dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
    val startTimeInMillis = dateFormat.parse(startTime).time.toString()
    println(startTimeInMillis)
  
}

Is there anything missing in above code that is causing different results ?


Solution

  • Yes, you are missing the fact that the timezone matters. If you don't specify a timezone, your result will be for the date/time you specify in the default timezone of the computer that the code is running on.

    For me, the epoch converter website gives the result "315549000000" for "1979/12/31 23:30:00", presumably because it's doing the conversion in JavaScript in the browser, and that is presumably using the timezone of my computer.

    If, instead, I enter "1979/12/31 23:30:00 GMT", I get "315531000000"

    So, if you want the two to match, you'll need to specify the timezone in the epoch converter, and also use the timezone in your Java/Kotlin code.

    For example, if you use the date string "1979/12/31 23:30:00 America/New_York" in the epoch converter, the following code should give you the same result:

    fun main(){ 
        val startTime = "1979/12/31 23:30:00 America/New_York"
        val dateFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss VV")
        val parsed = ZonedDateTime.parse(startTime, dateFormat);
        println(parsed.toInstant().toEpochMilli())
    }