Time Formatting Parsing in Haskell
In Haskell, we can work with time formatting and parsing using the time
library. Here’s how we can perform similar operations to the original example:
import Data.Time
import Data.Time.Format
import System.Locale (defaultTimeLocale)
main :: IO ()
main = do
-- Get the current time
now <- getCurrentTime
-- Format the current time according to RFC3339
putStrLn $ formatTime defaultTimeLocale (iso8601DateFormat (Just "%H:%M:%S%Z")) now
-- Parse a time string
let parsedTime = parseTimeOrError True defaultTimeLocale "%Y-%m-%dT%H:%M:%S%Z" "2012-11-01T22:08:41+00:00" :: UTCTime
print parsedTime
-- Custom time formatting
putStrLn $ formatTime defaultTimeLocale "%I:%M%p" now
putStrLn $ formatTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" now
putStrLn $ formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S.%q%z" now
-- Custom time parsing
let customParsedTime = parseTimeOrError True defaultTimeLocale "%I %M %p" "8 41 PM" :: UTCTime
print customParsedTime
-- Formatting with extracted components
let (year, month, day) = toGregorian $ utctDay now
let (TimeOfDay hour minute second) = timeToTimeOfDay $ utctDayTime now
putStrLn $ printf "%04d-%02d-%02dT%02d:%02d:%02d-00:00" year month day hour minute (floor second :: Int)
-- Handling parsing errors
case parseTimeM True defaultTimeLocale "%a %b %e %H:%M:%S %Y" "8:41PM" of
Just t -> print t
Nothing -> putStrLn "Error parsing time"
This Haskell code demonstrates time formatting and parsing using the time
library. Here’s a breakdown of the operations:
We use
getCurrentTime
to get the current time.The
formatTime
function is used to format times according to specified patterns. We use it with various format strings to demonstrate different outputs.For parsing, we use
parseTimeOrError
which will throw an error if the parsing fails. In a real-world application, you might want to useparseTimeM
which returns aMaybe
type, allowing for more graceful error handling.Haskell’s
time
library uses format strings similar to those in other languages. For example,"%Y-%m-%dT%H:%M:%S%Z"
is used to parse an ISO8601 formatted date-time string.We demonstrate extracting individual components of a time value using
toGregorian
for the date andtimeToTimeOfDay
for the time.Finally, we show how to handle parsing errors using
parseTimeM
which returns aMaybe
type.
Note that Haskell’s approach to time handling is somewhat different from imperative languages. It emphasizes type safety and pure functions, which can make some operations more verbose but also more robust.
When running this program, you’ll see output similar to the original example, with the current time formatted in various ways and the results of parsing operations.