Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a time value of type UTCTime from string in Haskell?

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.

like image 471
mntk123 Avatar asked Oct 02 '16 14:10

mntk123


1 Answers

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.
  • we partially apply parseTimeOrError, using defaultTimeLocale for the locale, and previously defined timeFormat for the expected format.
  • We now have a 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"))
  • 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 in timeFormat.
like image 55
tomahh Avatar answered Nov 15 '22 22:11

tomahh