Title here
Summary here
Our first example demonstrates time formatting and parsing in Standard ML. Here’s the full source code:
fun main() =
let
(* Helper function to print *)
fun p x = print (x ^ "\n")
(* Get current time *)
val t = Time.now()
(* Format time according to ISO 8601 *)
val formatted = Date.fmt "%Y-%m-%dT%H:%M:%S%z" (Date.fromTimeLocal t)
in
p formatted;
(* Time parsing *)
case Date.fromString "2012-11-01T22:08:41+00:00" of
SOME date => p (Date.toString date)
| NONE => p "Failed to parse date";
(* Custom formatting *)
p (Date.fmt "%I:%M%p" (Date.fromTimeLocal t));
p (Date.fmt "%a %b %d %H:%M:%S %Y" (Date.fromTimeLocal t));
p (Date.fmt "%Y-%m-%dT%H:%M:%S.%f%z" (Date.fromTimeLocal t));
(* Custom parsing *)
case Date.fromString "8:41 PM" of
SOME date => p (Date.toString date)
| NONE => p "Failed to parse time";
(* Numeric representation *)
let
val date = Date.fromTimeLocal t
in
print (String.concat [
Int.toString (Date.year date), "-",
StringCvt.padLeft #"0" 2 (Int.toString (Date.month date)), "-",
StringCvt.padLeft #"0" 2 (Int.toString (Date.day date)), "T",
StringCvt.padLeft #"0" 2 (Int.toString (Date.hour date)), ":",
StringCvt.padLeft #"0" 2 (Int.toString (Date.minute date)), ":",
StringCvt.padLeft #"0" 2 (Int.toString (Date.second date)),
"-00:00\n"
])
end;
(* Parsing error *)
case Date.fromString "8:41PM" of
SOME _ => p "Parsed successfully"
| NONE => p "Failed to parse time"
end
val _ = main()
In Standard ML, we use the Date
and Time
modules for time-related operations. The Date.fmt
function is used for formatting dates, while Date.fromString
is used for parsing.
To run the program, save it as time_formatting_parsing.sml
and use the SML interpreter:
$ sml time_formatting_parsing.sml
2023-06-15T10:30:45+0000
Thu Nov 1 22:08:41 2012
10:30AM
Thu Jun 15 10:30:45 2023
2023-06-15T10:30:45.123456+0000
Thu Jan 1 20:41:00 1970
2023-06-15T10:30:45-00:00
Failed to parse time
Note that the exact output will vary depending on the current time when you run the program.
Standard ML’s date and time handling is somewhat different from some other languages:
SOME date
or NONE
).Despite these differences, we can still perform similar time formatting and parsing operations in Standard ML.