Time and dates
UTCTime and NominalDiffTime
Data.Time in the boot libraries has three types worth knowing before the functions:
- UTCTime is an instant, stored as a day count and the seconds since midnight, with no time zone.
- NominalDiffTime is a difference between two instants, with Num and Show instances, so it prints as a number of seconds with an s suffix.
- Day and LocalTime are the calendar pieces and a time with a zone, which is what a user sees.
A program that needs a date should work in UTCTime and convert at the edge, because a local time with a zone is ambiguous twice a year and a bare date is not an instant.
A fixed time and a duration
The first program builds an instant from a literal with parseTimeOrError, which is the version that throws on a bad input, and then adds and subtracts:
module Main (main) where
import Data.Time
( UTCTime
, addUTCTime
, defaultTimeLocale
, diffUTCTime
, formatTime
, getCurrentTime
, parseTimeOrError
)
start :: UTCTime
start = parseTimeOrError True defaultTimeLocale "%Y-%m-%d %H:%M:%S" "2026-11-19 09:00:00"
main :: IO ()
main = do
let finish = addUTCTime (90 * 60) start
print (diffUTCTime finish start)
putStrLn (formatTime defaultTimeLocale "%Y-%m-%d %H:%M" start)
putStrLn (formatTime defaultTimeLocale "%H:%M:%S" finish)
now <- getCurrentTime
putStrLn ("the clock is after the course start: " ++ show (now > start))
ghc -Wall -O1 -o time time.hs
./time
5400s
2026-11-19 09:00
10:30:00
the clock is after the course start: True
addUTCTime takes seconds, not minutes, so the 90 minutes are written as 90 * 60. diffUTCTime gives the same 5400 seconds back with a s suffix, because the Show instance of NominalDiffTime prints seconds. The last line is real IO and its answer depends on the clock of the machine, which is why the program prints a comparison and not the instant itself.
Parsing a date that may be wrong
parseTimeM is the version that returns a Maybe, and that is the one to use on input a user typed:
module Main (main) where
import Data.Time (UTCTime, defaultTimeLocale, formatTime, parseTimeM)
parseDate :: String -> Maybe UTCTime
parseDate = parseTimeM True defaultTimeLocale "%Y-%m-%d"
main :: IO ()
main = do
print (parseDate "2026-11-19")
print (parseDate "19.11.2026")
mapM_ (print . formatTime defaultTimeLocale "%d %B %Y") (parseDate "2026-01-05")
ghc -Wall -O1 -o dates dates.hs
./dates
Just 2026-11-19 00:00:00 UTC
Nothing
"05 January 2026"
The bad input gives Nothing and not an exception, so the caller can print its own message. A date with no time of day is midnight UTC, which is why the first line ends in 00:00:00 UTC. The format string is the other half of the parsing format: %d %B %Y prints the day, the full month name in the locale and the year.
Measuring a computation
Two clock reads around a computation give a duration. The evaluate in the middle is not decoration: without it the sum is a thunk and the two reads would be microseconds apart, because nothing was computed yet. This is the laziness lesson applied to timing:
module Main (main) where
import Control.Exception (evaluate)
import Data.Time (diffUTCTime, getCurrentTime)
main :: IO ()
main = do
start <- getCurrentTime
total <- evaluate (sum [1 .. 1000000 :: Int])
finish <- getCurrentTime
print total
print (diffUTCTime finish start >= 0)
ghc -Wall -O1 -o measured measured.hs
./measured
500000500000
True
The second line is deliberately a comparison: the duration of a million additions is a few milliseconds and changes with the load of the machine, so the page prints that it was measured and not how long it took. The lesson on performance measurement later in the course takes five runs and reports the minimum and the median, which is the honest way to publish a number.
The clock and the machine
getCurrentTime reads the system clock, and its value is an IO UTCTime: two calls can differ, so it cannot be a pure function. Three practical notes:
- Read the clock once and pass the value down, instead of letting every function read it; then a test can pass a fixed instant.
- The clock can go backwards when the system time is adjusted, so measure an interval with the monotonic clock of GHC.Clock when the order matters.
- A time zone is a rule and not an offset: Data.Time.LocalTime has the database of the system for that, and a fixed offset is wrong twice a year.
The types are the guide: UTCTime for storage, ZonedTime for display, and NominalDiffTime for arithmetic. A function that takes a UTCTime as an argument is pure and testable, which is the shape every timestamped report should have.
Exercises
- Print the day of the week of a fixed date with formatTime and %A.
- Add a day to a UTCTime with addUTCTime (24 * 60 * 60) and check the result across a month boundary.
- Write parseDuration :: String -> Maybe NominalDiffTime for input such as 90m and 2h.
- Measure the same sum with and without evaluate and explain the difference.
- Explain why parseTimeOrError is a poor choice for user input and what it is good for.
- Format a UTCTime in two different formats and compare the strings.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a
UTCTime?Answer
An instant with no time zone
UTCTime is an instant in UTC; a ZonedTime or LocalTime is what a user sees.
-
What does
diffUTCTimereturn?Answer
A
NominalDiffTimeThe difference of two instants is a duration, and its Show instance appends the letter s.
-
What does
addUTCTime (90 * 60)add?Answer
90 minutes
The argument is a number of seconds, so 90 times 60 is 5400 seconds.
-
What does this program print?
module Main (main) where import Data.Time (addUTCTime, defaultTimeLocale, diffUTCTime, parseTimeOrError) main :: IO () main = print (diffUTCTime (addUTCTime 60 start) start) where start = parseTimeOrError True defaultTimeLocale "%Y-%m-%d" "2026-01-01"Answer
60s
Sixty seconds added and subtracted gives a difference of sixty seconds, printed with the s suffix.
-
Which function parses a date and returns a Maybe?
Answer
parseTimeMparseTimeM is the safe parser; parseTimeOrError throws on a bad input.
-
What does this program print?
module Main (main) where import Data.Time (UTCTime, defaultTimeLocale, formatTime, parseTimeM) main :: IO () main = putStrLn (maybe "bad" (formatTime defaultTimeLocale "%Y") (parseTimeM True defaultTimeLocale "%Y-%m-%d" "2026-11-19" :: Maybe UTCTime))Answer
2026
The date parses, so maybe takes the formatting branch and putStrLn prints the year without quotes.
-
Why is
evaluateimportant when timing a computation?Answer
Without it the result is a thunk and the work has not happened yet
Laziness means the sum is only computed when forced, and evaluate forces it between the two clock reads.
-
Why should a timestamped report take the time as an argument?
Answer
It stays a pure function and a test can pass a fixed instant
A function of a given time is reproducible; reading the clock inside makes the output depend on the run.
-
What does
formatTime defaultTimeLocale "%H:%M"print?Answer
The hours and minutes of a time
H is the hour in 24-hour form and M the minute, as the fixed-time program showed.
-
What is a
NominalDiffTimegood for?Answer
Adding and subtracting intervals, and measuring elapsed time
It is the duration type: Num, so you can add it to an instant, and Show, so it prints in seconds.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev