Epoch in Racket

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

#lang racket

(require racket/date)

(define (main)
  ; Use current-seconds, current-milliseconds, or current-inexact-milliseconds
  ; to get elapsed time since the Unix epoch in seconds or milliseconds.
  (define now (current-date))
  (displayln now)
  
  (displayln (current-seconds))
  (displayln (current-milliseconds))
  (displayln (current-inexact-milliseconds))
  
  ; You can also convert integer seconds or milliseconds
  ; since the epoch into the corresponding date.
  (displayln (seconds->date (current-seconds)))
  (displayln (seconds->date (/ (current-milliseconds) 1000))))

(main)

To run the program:

$ racket epoch.rkt
#<date Wed Nov 01 10:30:00 GMT-04:00 2023>
1698846600
1698846600000
1698846600000.0
#<date Wed Nov 01 10:30:00 GMT-04:00 2023>
#<date Wed Nov 01 10:30:00 GMT-04:00 2023>

In Racket, we use current-seconds, current-milliseconds, and current-inexact-milliseconds to get the elapsed time since the Unix epoch in seconds and milliseconds. Racket doesn’t have a built-in function for nanoseconds, so we use current-inexact-milliseconds as the closest equivalent.

We can convert seconds back to a date object using the seconds->date function. Note that Racket’s date structure includes both date and time information.

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