Search code examples
haskelltimeepochgregorian-calendar

How to convert epoch to gregorian datetime in haskell


Let's say I have an integer representing Epoch time, for example epoch = 1499055085, and I want to convert it to UTCTime in Haskell. How can I do this?

In other languages this is a very trivial task, why is it so difficult in haskell?


Solution

  • Who says it is difficult?

    You can simply use fromIntegral :: (Integral a, Num b) => a -> b to convert the epoch (an integer) to POSIXTime.

    Next we can use posixSecondsToUTCTime :: POSIXTime -> UTCTime to obtain the UTCTime, and finally we use the utctDay :: UTCTime -> Day to get the day part of the UTCTime.

    In case you want a (year,month,day) tuple, we can use the toGregorian :: Day -> (Integer,Int,Int) method.

    So we can use the following method:

    import Data.Time.Calendar(toGregorian)
    import Data.Time.Clock(utctDay,UTCTime)
    import Data.Time.Clock.POSIX(posixSecondsToUTCTime)
    
    epochToUTC :: Integral a => a -> UTCTime
    epochToUTC = posixSecondsToUTCTime . fromIntegral
    
    epochToGregorian :: Integral a => a -> (Integer,Int,Int)
    epochToGregorian = toGregorian . utctDay . epochToUTC
    

    And then for instance:

    Main> epochToGregorian 1234567
    (1970,1,15)
    Main> epochToGregorian 123456789
    (1973,11,29)
    Main> epochToGregorian 1234567890
    (2009,2,13)