Stream: beginners

Topic: DateTime from Epoch


view this post on Zulip Luke Boswell (Nov 15 2023 at 00:04):

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.

view this post on Zulip Luke Boswell (Nov 15 2023 at 00:05):

It is calculating the correct year, month and day... but the hours:minutes:seconds is really off and I'm not sure why

view this post on Zulip Richard Feldman (Nov 15 2023 at 00:40):

oh I have a WIP thing that does this both ways

view this post on Zulip Richard Feldman (Nov 15 2023 at 00:42):

https://github.com/rtfeldman/roc-iso8601

view this post on Zulip Richard Feldman (Nov 15 2023 at 00:42):

it's based on https://github.com/rtfeldman/elm-iso8601-date-strings/blob/master/src/Iso8601.elm

view this post on Zulip Brendan Hansknecht (Nov 15 2023 at 01:16):

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,
        }

view this post on Zulip Brendan Hansknecht (Nov 15 2023 at 01:16):

That said, it has 1 too many hours, minutes, and seconds for some reason with that change.

view this post on Zulip Brendan Hansknecht (Nov 15 2023 at 01:17):

Ah, also need to change:

    seconds = millis // 1000
    minutes = seconds // 60
    hours = minutes // 60

view this post on Zulip Brendan Hansknecht (Nov 15 2023 at 01:17):

instead of the current divCeil

view this post on Zulip Luke Boswell (Nov 15 2023 at 01:17):

Just got it working, and added a bunch of test cases

view this post on Zulip Luke Boswell (Nov 15 2023 at 01:18):

Yeah, needed div trunc

view this post on Zulip Luke Boswell (Nov 15 2023 at 01:18):

I updated the gist with the correct version.

view this post on Zulip Luke Boswell (Nov 15 2023 at 01:19):

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