Home > Enterprise >  Correct format string to parse a date time in Haskell
Correct format string to parse a date time in Haskell

Time:09-17

I'm trying to parse a datetime using Haskell's Date.Time package, but I don't seem to have the format right.

Here are a few examples of dates that I'm trying to parse:

2015-01-01T01:00:00.000Z
2015-01-11T03:00:00.000Z
2015-01-11T03:00:00.000Z

I have a function like:

parseStringToDateTime :: String -> UTCTime
parseStringToDateTime = parseTimeOrError False defaultTimeLocale "%Y-%m-%d %HH:%MM:%SS"

But this isn't quite right and I get a runtime error.

What's the correct format string to parse a datetime like this?

CodePudding user response:

Using time-1.9.3 I managed to format your date-time strings like this:

λ> import Date.Time
λ> import Data.Time.Format.ISO8601 -- I think it's Date.Time.Format in newer versions
λ> formatParseM (iso8601Format @UTCTime) "2015-01-11T03:00:00.000Z" >>= print
2015-01-11 03:00:00 UTC

Now we can replicate parseTimeOrError for your use case:

λ> parseStringToDateTime s =  maybe (error $ "bad date-time string "    s) id $ formatParseM (iso8601Format @UTCTime) s
λ> parseStringToDateTime "2015-01-11T03:00:00.000Z" 
2015-01-11 03:00:00 UTC
λ> parseStringToDateTime "BAD"
*** Exception: bad date-time string BAD
  • Related