Time Formatting Parsing in Scheme
(import (scheme base)
(scheme time))
(define (main)
(define (p . args) (for-each display args) (newline))
; Here's a basic example of formatting a time
; according to RFC3339, using the corresponding layout
; constant.
(let ((t (current-time)))
(p (date->string t "~Y-~m-~dT~H:~M:~SZ")))
; Time parsing uses the same layout values as formatting.
(let-values (((t1 e) (string->date "2012-11-01T22:08:41+00:00" "~Y-~m-~dT~H:~M:~SZ")))
(p t1))
; Format and Parse use example-based layouts. Usually
; you'll use a predefined format string for these layouts, but
; you can also supply custom layouts.
(let ((t (current-time)))
(p (date->string t "~I:~M~p"))
(p (date->string t "~a ~b ~e ~H:~M:~S ~Y"))
(p (date->string t "~Y-~m-~dT~H:~M:~S.~N~z")))
(let-values (((t2 e) (string->date "8 41 PM" "~I ~M ~p")))
(p t2))
; For purely numeric representations you can also
; use standard string formatting with the extracted
; components of the time value.
(let ((t (current-time)))
(format #t "~4d-~02d-~02dT~02d:~02d:~02d-00:00~%"
(date-year t) (date-month t) (date-day t)
(date-hour t) (date-minute t) (date-second t)))
; string->date will return an error on malformed input
; explaining the parsing problem.
(let-values (((ignore e) (string->date "8:41PM" "~a ~b ~e ~H:~M:~S ~Y")))
(p e)))
(main)
This Scheme code demonstrates time formatting and parsing, similar to the original Go example. Here are some key points about the translation:
Scheme doesn’t have a built-in module for advanced time operations, so we’re using basic time functions from the
(scheme time)
library.The
Format
andParse
operations in Go are replaced withdate->string
andstring->date
in Scheme.The format strings are different in Scheme. For example,
~Y-~m-~d
is used for year-month-day instead of2006-01-02
.Error handling is done through multiple return values in Scheme, similar to Go.
The
Printf
style formatting in Go is replaced with Scheme’sformat
function.Scheme doesn’t have a direct equivalent to Go’s
time.RFC3339
constant, so we use the format string directly.
When you run this program, it will output various formatted times and demonstrate parsing time strings. The exact output will depend on the current time when you run the program.
Remember that the exact behavior might vary depending on the Scheme implementation you’re using, as time handling can be implementation-specific in Scheme.