Here we demonstrate getting the current time, comparing two moments in time, and converting between a few different timestamp representations.
None of the code here involves time zones. This program will not display the same current time as the clock on your wall, but it will behave the same regardless of what part of the world it runs in. This makes the types in this example suitable for a “machine” view of time such as you might use for recording the times of events in a log file, or for scheduling tasks in a multi-threaded or distributed application.
In this example we’ve included some optional type annotations for clarity. The scoped type variables language extension is required to let us write type annotations in a pattern context (on the left-hand side of either the
All of our imports here come from the
We will convert timestamps to their string representations using the formatTime function from the
We will parse strings as timestamp values using the parseTimeM function from the
The getCurrentTime action provides the current time from the system clock as a
UTCTime value. A value of the
UTCTime type represents a moment in time according to the coordinated universal time standard.
Sometimes we receive a time in some string format that we need to interpret by parsing the string.
We use a format string (in this case, “%Y-%m-%d %H:%M:%S”) to specify how to parse the timestamp. See the Data.Time.Format module for documentation on how to write a format string.
We also use format strings to convert a
UTCTime value to a
String. Here we use the format “%Y-%m-%d” to print the date portion of the timestamp, and then “%I:%M %p” to print the time of day in a 12-hour clock style.
Use addUTCTime to add some offset to a timestamp. Here we define
t2_utc to be a time that is 15 seconds into the future from
Use diffUTCTime to subtract one time from another and determine the amount of time elapsed from one moment to the next.
POSIX time is simpler, but UTC is easier to read at a glance.