Time in Racket

#lang racket

(require racket/date)

(define (p . args)
  (for-each displayln args))

(define (main)
  ; We'll start by getting the current time.
  (define now (current-date))
  (p now)

  ; You can build a date struct by providing the
  ; year, month, day, etc. Times are always associated
  ; with a time zone.
  (define then (date* 2009 11 17 20 34 58 651387237 0 "UTC"))
  (p then)

  ; You can extract the various components of the date
  ; value as expected.
  (p (date-year then))
  (p (date-month then))
  (p (date-day then))
  (p (date-hour then))
  (p (date-minute then))
  (p (date-second then))
  (p (date-nanosecond then))
  (p (date-time-zone-name then))

  ; The day of the week is also available.
  (p (date-week-day then))

  ; These functions compare two dates, testing if the
  ; first occurs before, after, or at the same time
  ; as the second, respectively.
  (p (date<? then now))
  (p (date>? then now))
  (p (date=? then now))

  ; The time-difference function returns a time-duration struct
  ; representing the interval between two times.
  (define diff (time-difference (date->time-utc now) 
                                (date->time-utc then)))
  (p diff)

  ; We can compute the length of the duration in
  ; various units.
  (p (/ (time-duration-nanoseconds diff) 3600000000000))  ; hours
  (p (/ (time-duration-nanoseconds diff) 60000000000))    ; minutes
  (p (/ (time-duration-nanoseconds diff) 1000000000))     ; seconds
  (p (time-duration-nanoseconds diff))

  ; You can use date-add to advance a date by a given
  ; duration, or with a negative duration to move backwards.
  (p (date->string (date-add then diff)))
  (p (date->string (date-add then (time-duration- diff)))))

(main)

This Racket program demonstrates various operations with dates and times, similar to the original example. Here’s a breakdown of the translation:

  1. We use #lang racket to specify the Racket language.
  2. We import the racket/date module for date and time operations.
  3. We define a p function to mimic the fmt.Println functionality.
  4. In the main function, we perform various date and time operations:
    • Get the current date using current-date.
    • Create a specific date using date*.
    • Extract components of a date using accessor functions like date-year, date-month, etc.
    • Compare dates using date<?, date>?, and date=?.
    • Calculate the difference between dates using time-difference.
    • Perform arithmetic on dates using date-add.

Note that Racket’s date and time functions work slightly differently from those in other languages. For example, Racket uses a date struct to represent both dates and times, and time zones are represented as offsets from UTC.

To run this program, save it as time.rkt and execute it using the Racket interpreter:

$ racket time.rkt

This will output the results of various date and time operations, similar to the original example.