I've been trying to write an algorithm to convert milliseconds since unix epoch to a date time string. I.e. 1700005179053 -> "2023-11-14 23:39:39"
. This gist is my current attempt, and I think I am really close, but I haven't quite got it working.
I'm not sure if there is a better way to do this, but thought I might post here in case anyone has any ideas or pointers.
$ roc test DateTime.roc
── EXPECT FAILED ──────────────────────────────────────────────── DateTime.roc ─
This expectation failed:
107│> expect # :sad face:
108│> str = 1700005179053 |> epochMillisToDateTime |> toStr
109│> str == "2023-11-14 23:39:39"
When it failed, these variables had these values:
str : Str
str = "2023-11-14 336:20140:1208380"
1 failed and 19 passed in 591 ms.
It is calculating the correct year, month and day... but the hours:minutes:seconds is really off and I'm not sure why
oh I have a WIP thing that does this both ways
https://github.com/rtfeldman/roc-iso8601
it's based on https://github.com/rtfeldman/elm-iso8601-date-strings/blob/master/src/Iso8601.elm
Your else case is leaving the days in the hours, your hours in the minutes, and minutes in the seconds:
else
{
year: current.year,
month: current.month,
day: current.day,
minutes: 0,
seconds: 0,
hours: current.hours % 24,
minutes: current.minutes % 60,
seconds: current.seconds % 60,
}
That said, it has 1 too many hours, minutes, and seconds for some reason with that change.
Ah, also need to change:
seconds = millis // 1000
minutes = seconds // 60
hours = minutes // 60
instead of the current divCeil
Just got it working, and added a bunch of test cases
Yeah, needed div trunc
I updated the gist with the correct version.
I realised that I should work my way up from a small number of milliseconds since epoch with my tests rather than just trying a current time. :oops:
Last updated: Jul 06 2025 at 12:14 UTC