Search code examples
dateelm

rata die to unix time


I am trying to convert Date.Date from the justinmimbs/date package to Time.Posix from elm/time or an integer of milliseconds since UNIX epoch.

my current approach is the following but it doesn't seem to work properly.

dateToPosixTime : Date.Date -> Time.Posix
dateToPosixTime date =
    Time.millisToPosix (Date.toRataDie date - 719162 * (1000 * 60 * 60 * 24))

(719162 is the offset of Jan 1, 1970 to Jan 1, 0001)

This seemed to work, but it doesn't give me working results anymore

Another approach:

dateToPosixTime : Date.Date -> Time.Posix
dateToPosixTime date =
    Time.millisToPosix ((Date.toRataDie date - epochStartOffset) * (1001 * 60 * 60 * 24) - (1000 * 60 * 60 * 24))

Solution

  • Ok, basically the second approach I described works, if you don't accidentally write 1001 * 60 * 60 * 24 instead of the correct 1000 * 60 * 60 * 24, because one second only has 1000 milliseconds, not 1001.

    The working code therefore is:

    epochStartOffset : Int
    epochStartOffset =
        719162
    
    
    dateToPosixTime : Date.Date -> Time.Posix
    dateToPosixTime date =
        Time.millisToPosix ((Date.toRataDie date - epochStartOffset) * (1000 * 60 * 60 * 24) - (1000 * 60 * 60 * 24))