Time Formatting Parsing in Wolfram Language

Our first example demonstrates time formatting and parsing in Wolfram Language. Here’s the full source code:

(* Import necessary packages *)
Needs["DateStringFormat`"]

(* Define a function to print results *)
p[x_] := Print[x]

(* Get the current time *)
t = Now;

(* Format the current time according to ISO 8601 (similar to RFC3339) *)
p[DateString[t, {"ISODateTime", "TimeZone"}]]

(* Parse a time string *)
t1 = DateObject["2012-11-01T22:08:41+00:00", {"ISODateTime", "TimeZone"}];
p[t1]

(* Custom time formatting *)
p[DateString[t, {"Hour12", ":", "Minute", "AMPM"}]]
p[DateString[t, {"DayName", " ", "MonthName", " ", "Day", " ", "Year"}]]
p[DateString[t, {"ISODateTime", ".", "Millisecond", "TimeZone"}]]

(* Custom time parsing *)
form = {"Hour12", ":", "Minute", " ", "AMPM"};
t2 = DateObject["8:41 PM", form];
p[t2]

(* Numeric representation of time *)
Print[StringForm[
  "`1`-`2`-`3`T`4`:`5`:`6`-00:00",
  DateValue[t, "Year"],
  DateValue[t, "Month"],
  DateValue[t, "Day"],
  DateValue[t, "Hour"],
  DateValue[t, "Minute"],
  DateValue[t, "Second"]
]]

(* Error handling in parsing *)
Check[
  DateObject["8:41PM", {"DayName", " ", "MonthName", " ", "Day", " ", "Year"}],
  p[$Failed]
]

In Wolfram Language, we use the DateString function for formatting dates and times, and DateObject for parsing them. The DateStringFormat package provides additional formatting options.

When running this script, you’ll see output similar to:

2023-05-15T10:30:45+01:00
2012-11-01T22:08:41+00:00
10:30 AM
Monday May 15 2023
2023-05-15T10:30:45.123+01:00
0000-01-01T20:41:00.
2023-05-15T10:30:45-00:00
$Failed

Note that Wolfram Language’s date and time handling is more flexible than Go’s. It doesn’t require a specific reference time for formatting patterns. Instead, it uses descriptive strings or symbols to specify date and time components.

Error handling in Wolfram Language is typically done using functions like Check or Quiet, which allow you to specify what should happen if an error occurs.

This example demonstrates basic time formatting and parsing in Wolfram Language, showing how to work with different date formats, parse time strings, and handle potential errors in parsing.