Time Formatting Parsing in Racket

Here’s the Racket translation of the time formatting and parsing example:

#lang racket

(require racket/date)

;; Here's a basic example of formatting a time
;; according to ISO 8601, which is similar to RFC3339.
(define current-time (current-date))
(printf "~a\n" (date->iso8601 current-time))

;; Time parsing uses string->date function in Racket.
(define t1 (string->date "2012-11-01T22:08:41Z" "~Y-~m-~dT~H:~M:~SZ"))
(printf "~a\n" t1)

;; Racket uses srfi/19 date-format for custom formatting.
;; Here are some examples:
(printf "~a\n" (date->string current-time "~I:~M~p"))
(printf "~a\n" (date->string current-time "~a ~b ~e ~H:~M:~S ~Y"))
(printf "~a\n" (date->string current-time "~Y-~m-~dT~H:~M:~S.~N~z"))

;; For parsing custom formats:
(define form "~I ~M ~p")
(define t2 (string->date "8 41 PM" form))
(printf "~a\n" t2)

;; For purely numeric representations you can also
;; use standard string formatting with the extracted
;; components of the time value.
(printf "~a-~a-~aT~a:~a:~a-00:00\n"
        (date-year current-time)
        (date-month current-time)
        (date-day current-time)
        (date-hour current-time)
        (date-minute current-time)
        (date-second current-time))

;; string->date will raise an exception on malformed input.
(with-handlers ([exn:fail? (lambda (exn) (printf "Error: ~a\n" (exn-message exn)))])
  (string->date "8:41PM" "~a ~b ~e ~H:~M:~S ~Y"))

This Racket code demonstrates time formatting and parsing, similar to the original example. Here are the key points:

  1. Racket uses the racket/date module for date and time operations.

  2. For basic ISO 8601 formatting (similar to RFC3339), we use date->iso8601.

  3. Parsing uses the string->date function, which takes a date string and a format string.

  4. Custom formatting is done with date->string, using format specifiers from srfi/19.

  5. Racket doesn’t have built-in constants for standard date formats, so we define them as strings.

  6. For purely numeric formatting, we can extract individual components of the date using functions like date-year, date-month, etc.

  7. Error handling for parsing is done using with-handlers, which is similar to try-catch in other languages.

When you run this program, it will output the current time in various formats, parse some time strings, and demonstrate error handling for malformed input. The exact output will depend on the current time when you run it, but it will be similar in structure to the original example.