Chris Stryczynski
Chris Stryczynski

Reputation: 33861

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

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.

Upvotes: 3

Views: 1743

Answers (2)

Manoj R
Manoj R

Reputation: 3247

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)

Upvotes: 3

Chris Stryczynski
Chris Stryczynski

Reputation: 33861

import Data.Time.Calendar
import Data.Time

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

Upvotes: 7

Related Questions