Epoch in Idris

import Data.Time

main : IO ()
main = do
    now <- epochTime

    putStrLn $ show now

    let seconds = cast now
    let milliseconds = seconds * 1000
    let nanoseconds = seconds * 1000000000

    putStrLn $ show seconds
    putStrLn $ show milliseconds
    putStrLn $ show nanoseconds

    let fromSeconds = fromEpochTime seconds
    let fromNanoseconds = addTime (fromEpochTime 0) (secondsToNanoseconds seconds)

    putStrLn $ show fromSeconds
    putStrLn $ show fromNanoseconds

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Idris.

We use epochTime from the Data.Time module to get the current time as seconds since the Unix epoch.

now <- epochTime
putStrLn $ show now

To get milliseconds and nanoseconds, we multiply the seconds by 1000 and 1000000000 respectively. Note that Idris doesn’t have built-in functions for milliseconds and nanoseconds like some other languages, so we’re performing the calculations manually.

let seconds = cast now
let milliseconds = seconds * 1000
let nanoseconds = seconds * 1000000000

putStrLn $ show seconds
putStrLn $ show milliseconds
putStrLn $ show nanoseconds

You can also convert integer seconds or nanoseconds since the epoch into the corresponding DateTime.

let fromSeconds = fromEpochTime seconds
let fromNanoseconds = addTime (fromEpochTime 0) (secondsToNanoseconds seconds)

putStrLn $ show fromSeconds
putStrLn $ show fromNanoseconds

To run the program, save it as Epoch.idr and use the Idris compiler:

$ idris -o epoch Epoch.idr
$ ./epoch
1685123456.0
1685123456
1685123456000
1685123456000000000
2023-05-26 20:37:36 UTC
2023-05-26 20:37:36 UTC

Note that the exact output will depend on when you run the program.

Next, we’ll look at another time-related task: time parsing and formatting.