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.
1 Answer 1
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:
timeFormatis simply a string, describing how we expect the time to be passed to us.- we partially apply
parseTimeOrError, usingdefaultTimeLocalefor the locale, and previously definedtimeFormatfor the expected format. - We now have a
understandTimefunction, that can take in a time as aString. When using it, we need to explicitly set the expected output type toUTCTime(this is whattime :: UTCTimedoes). If we were to useunderstandTimewithin the context of a function that already expects aUTCTime, this would be unnecessary (for exampleaddUTCTime 1000 (understandTime "10:30:20")) - We get back
time. Note that the year, day, month and timezone default to 1970年01月01日 and UTC because we do not explicitly read them intimeFormat.
8 Comments
Not in scope: 'parseTimeOrError', which module to import?Couldn't match expected type 'UTCTime' with actual type Maybe t0' In the return type of a call of 'understandTime'`time :: Maybe UTCTime, if you update your answer, I'll accept it.parseTime is documented as outdated.