Epoch in Scheme

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

(import (scheme base)
        (scheme time))

(define (main)
  ; Use current-second, current-jiffy, and jiffies-per-second to get
  ; elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds.
  (let ((now (current-second)))
    (display (current-second))
    (newline)

    (display now)
    (newline)

    ; Convert jiffies to milliseconds
    (display (inexact->exact (round (* (/ (current-jiffy) 
                                          (jiffies-per-second)) 
                                       1000))))
    (newline)

    ; Convert jiffies to nanoseconds
    (display (inexact->exact (round (* (/ (current-jiffy) 
                                          (jiffies-per-second)) 
                                       1000000000))))
    (newline)

    ; You can also convert integer seconds or nanoseconds
    ; since the epoch into the corresponding time.
    (display (seconds->date now))
    (newline)

    (display (seconds->date (/ (current-jiffy) (jiffies-per-second))))
    (newline)))

(main)

To run the program, save it to a file (e.g., epoch.scm) and use your Scheme interpreter to execute it. The exact command may vary depending on your Scheme implementation.

$ scheme --script epoch.scm
1685123456
1685123456
1685123456789
1685123456789000000
#<date 2023-05-26T12:34:56Z>
#<date 2023-05-26T12:34:56Z>

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

In Scheme, we use current-second to get the current time in seconds since the Unix epoch. For more precise measurements, we use current-jiffy and jiffies-per-second. The jiffy is a unit of time in Scheme, but its exact duration can vary between implementations. We convert jiffies to milliseconds and nanoseconds by dividing by jiffies-per-second and then multiplying by 1000 or 1000000000, respectively.

The seconds->date function is used to convert seconds since the epoch to a date object, which is roughly equivalent to converting integer seconds to a time object in the original example.

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