Epoch in PureScript

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 PureScript.

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)
import Data.DateTime.Instant (unInstant)
import Effect.Now (now)
import Data.Time.Duration (Milliseconds(..), Seconds(..), newtypeToNumber)

main :: Effect Unit
main = do
  -- Use `now` to get the current time
  currentTime <- now
  log $ show currentTime

  -- Convert to seconds, milliseconds, and nanoseconds since the Unix epoch
  let (Milliseconds ms) = unInstant currentTime
  let seconds = ms / 1000.0
  let nanoseconds = ms * 1000000.0

  log $ show seconds
  log $ show ms
  log $ show nanoseconds

  -- You can also convert integer seconds or nanoseconds
  -- since the epoch into the corresponding time.
  -- PureScript doesn't have built-in functions for this,
  -- so we'll just demonstrate the concept
  log $ show $ Seconds seconds
  log $ show $ Milliseconds ms

To run this program, you would typically use the PureScript compiler (purs) and Node.js:

$ spago run
2023-06-09 12:34:56.789 UTC
1686315296.789
1686315296789.0
1686315296789000000.0
(Seconds 1686315296.789)
(Milliseconds 1686315296789.0)

In this PureScript version:

  1. We use the Effect.Now module to get the current time.
  2. The unInstant function from Data.DateTime.Instant is used to extract the milliseconds since the Unix epoch.
  3. We manually calculate seconds and nanoseconds from the milliseconds value.
  4. PureScript doesn’t have built-in functions to convert seconds or nanoseconds back to a time type, so we just demonstrate the concept by showing the Seconds and Milliseconds newtypes.

Note that PureScript’s ecosystem might not have exact equivalents for all of Go’s time-related functions, so some adaptations were necessary. The core concept of working with Unix epoch times is preserved.

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