How do I create a UTCTime value using the time library in Haskell?

1.6k Views Asked by At

I've got a year, month, day, hour and minute value (all of them are of type Int) - how can I convert these to a UTCTime?

Just as How do I create a UTCTime from Int values, using the thyme library in Haskell? but using the time library instead.

2

There are 2 best solutions below

1
On BEST ANSWER
import Data.Time.Calendar
import Data.Time

example :: UTCTime
example = UTCTime (fromGregorian 2018 10 27) (secondsToDiffTime 0)
0
On

Putting it here for reference. Check two methods parseTimeM and parseTimeOnError. Both you can get from here. parseTimeM is safe version while parseTimeOnError is unsafe (throws exception).

I had used parseTimeOnError before. You will need to convert the given information in string in specific format and call the function with format and the string as input.

import Data.Time
import Data.Time.Format
import Data.Time.Clock
import Text.Printf

getDateString :: Int -> Int -> Int -> Int -> Int -> String
getDateString year month day hour minute = (printf "%02d" month) ++ "/" ++ (printf "%02d" day) ++ "/" ++ show year ++ " " ++ show hour ++ ":" ++ show minute

getTheUTCDate :: String -> UTCTime 
getTheUTCDate strDate = parseTimeOrError True defaultTimeLocale "%D %R" strDate

main = do 
          let p = getDateString 12 7 6 23 45 
          print ("Hello ", " ", getTheUTCDate p)