Creating a countdown in Elm from two posix timestamps

Viewed 80

Basically I am trying to create a countdown from the difference of two UNIX timestamps.

My goal is to create a countdown like this: 130:04:23 with 130 being the hours, 04 being the minutes and 23 being the seconds between the two dates.

toCountDown : Time.Posix -> Time.Posix -> String
toCountDown now end =
    let
        differenceMillis =
            Time.posixToMillis end - Time.posixToMillis now
        hour =
            String.fromInt (differenceMillis // 1000 // 60 // 60)
        minute =
            String.fromInt (remainderBy 60 (differenceMillis // 1000 // 60))
        second =
            String.fromInt (remainderBy 60 (differenceMillis // 1000))
    in
    hour ++ ":" ++ minute ++ ":" ++ second

My code works for dates less than 24 hours apart but not more than that. Negative numbers of milliseconds between the dates also don't really work.

1 Answers

The solution is to use modBy, not remainderBy. The correct code therefore is:

toCountDown : Time.Posix -> Time.Posix -> String
toCountDown now end =
    let
        differenceMillis =
            Time.posixToMillis end - Time.posixToMillis now
        hour =
            String.fromInt (differenceMillis // 1000 // 60 // 60)
        minute =
            String.fromInt (modBy 60 (differenceMillis // 1000 // 60))
        second =
            String.fromInt (modBy 60 (differenceMillis // 1000))
    in
    hour ++ ":" ++ minute ++ ":" ++ second
Related