3

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.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286

2 Answers2

7
import Data.Time.Calendar
import Data.Time

example :: UTCTime
example = UTCTime (fromGregorian 2018 10 27) (secondsToDiffTime 0)
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
  • 3
    You should probably use [secondsToDiffTime](https://hackage.haskell.org/package/time-1.9.2/docs/Data-Time-Clock.html#v:secondsToDiffTime) or [picosecondsToDiffTime](https://hackage.haskell.org/package/time-1.9.2/docs/Data-Time-Clock.html#v:picosecondsToDiffTime) instead `toEnum`. – typetetris Oct 27 '18 at 15:34
3

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)
Manoj R
  • 3,197
  • 1
  • 21
  • 36