This is a follow-up question to the one I asked just a little while ago.
I couldn't find a single example (sorry for my Google skills) on the Haskell site which shows how to use the Data.Time
functions to convert a formatted String
to UTCTime
and then be able to add/subtract minutes/seconds from that and convert back the UTCTime
to formatted String
.
I am looking for an example that shows how to convert a String
(e.g. like "10:20:30"
to UTCTime
and then add 1000 seconds to that time. How to do this Haskell using the Data.Time
library without using IO at all?
The type of the function should be FormatTime -> String -> UTCTime
.
The function should use TimeLocale
or FormatTime
as locale/formatting is needed.
There are so many functions in the library and so many types that it just baffling. readTime
, TimeLocale
, ParseTime t
, NominalDiffTime
, Time
and what not.
Please do not just point to docs on the Haskell site. Most of the docs there are just a dump of type signatures from the source code, without almost any examples. Sorry if this is coming as rant, but I have spent a lot of time trying to figure out something from those docs.
Compare this to Python docs on time. So many beautiful examples. Thank god, there is SO.
import Data.Time
timeFormat = "%H:%M:%S"
understandTime = parseTimeOrError True defaultTimeLocale timeFormat
time :: UTCTime
time = understandTime "10:30:20"
λ> time
1970-01-01 10:30:20 UTC
Let's break down what's going on:
timeFormat
is simply a string, describing how we expect the time to be passed to us.parseTimeOrError
, using defaultTimeLocale
for the locale, and previously defined timeFormat
for the expected format.understandTime
function, that can take in a time as a String
. When using it, we need to explicitly set the expected output type to UTCTime
(this is what time :: UTCTime
does). If we were to use understandTime
within the context of a function that already expects a UTCTime
, this would be unnecessary (for example addUTCTime 1000 (understandTime "10:30:20")
)time
. Note that the year, day, month and timezone default to 1970-01-01 and UTC because we do not explicitly read them in timeFormat
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With