Reputation: 567
I have time as milliseconds since 1970-01-01 00:00 UTC. How can I convert it to UTCTime (Integer -> UTCTime)? I need UTCTime for inserting it in MongoDB.
Thank you!
Upvotes: 2
Views: 1723
Reputation: 338
You can use the function posixSecondsToUTCTime
in Data.Time.Clock.POSIX. As your value is in milliseconds you need to divide it by 1000 first. Here's an example:
import Data.Time.Clock.POSIX
import Data.Time.Clock.UTC
millisToUTC :: Integer -> UTCTime
millisToUTC t = posixSecondsToUTCTime $ (fromInteger t) / 1000
Upvotes: 3
Reputation: 52029
Here's how to create a UTCTime and add a number of seconds to it:
import Data.Time.Calendar
import Data.Time.Clock
-- 1/1/1900 as a Day
jan_1_1900_day = fromGregorian 1900 1 1 :: Day
-- 1/1/1900 as a UTCTime
jan_1_1900_time = UTCTime jan_1_1900_day 0
secs = 86400+3600 -- number of seconds to add to 1/1/1900
-- = 1 day + 1 hour
-- add some seconds to 1/1/1900 00:00:00
myTime = addUTCTime (fromIntegral secs) jan_1_1900_time
showTime t = (utctDay t, utctDayTime t) -- to see inside a UTCTime
main = do
print $ showTime jan_1_1900_time
print $ showTime myTime
The output is:
(1900-01-01,0s)
(1900-01-02,3600s)
The first argument to addUTCTime
is a NominalDiffTime which has both a Num
instance and an Enum
instance.
Using the Num
instance, fromIntegral x
will create a NominalDiffTime of x
seconds.
Using the Enum
instance, toEnum x
will create a NominalDiffTime of x
picoseconds.
So if you want millisecond resolution on your times, you can use this recipe:
millis = (2*86400+3600)*1000 -- milliseconds to add = 2 days + 1 hour
myTime' = addUTCTime (toEnum (millis*10^9)) jan_1_1900_time
And then print $ showtime myTime'
results in:
(1900-01-03,3600s)
Upvotes: 1