haddocks: Example how to obtain POSIX int timestamps. Fixes #106
[packages/time.git] / lib / Data / Time / Clock / POSIX.hs
1 -- | POSIX time, if you need to deal with timestamps and the like.
2 -- Most people won't need this module.
3 --
4 -- If you want to convert POSIX time to integer/word timestamps,
5 -- consider the following example:
6 --
7 -- > import Data.Time.Clock (UTCTime, getCurrentTime, nominalDiffTimeToSeconds)
8 -- > import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
9 -- > import Data.Int (Int64)
10 -- >
11 -- > nanosSinceEpoch :: UTCTime -> Int64
12 -- > nanosSinceEpoch =
13 -- > floor . (1e9 *) . nominalDiffTimeToSeconds . utcTimeToPOSIXSeconds
14 -- >
15 -- > main :: IO ()
16 -- > main = do
17 -- > u <- getCurrentTime :: IO UTCTime
18 -- > print (nanosSinceEpoch u)
19 module Data.Time.Clock.POSIX
20 (
21 posixDayLength,POSIXTime,posixSecondsToUTCTime,utcTimeToPOSIXSeconds,getPOSIXTime,getCurrentTime,
22 systemToPOSIXTime,
23 ) where
24
25 import Data.Time.Clock.Internal.POSIXTime
26 import Data.Time.Clock.Internal.UTCTime
27 import Data.Time.Clock.System
28 import Data.Time.Calendar.Days
29 import Data.Fixed
30
31 posixSecondsToUTCTime :: POSIXTime -> UTCTime
32 posixSecondsToUTCTime i = let
33 (d,t) = divMod' i posixDayLength
34 in UTCTime (addDays d systemEpochDay) (realToFrac t)
35
36 utcTimeToPOSIXSeconds :: UTCTime -> POSIXTime
37 utcTimeToPOSIXSeconds (UTCTime d t) =
38 (fromInteger (diffDays d systemEpochDay) * posixDayLength) + min posixDayLength (realToFrac t)
39
40 systemToPOSIXTime :: SystemTime -> POSIXTime
41 systemToPOSIXTime (MkSystemTime s ns) = (fromIntegral s) + (fromIntegral ns) * 1E-9
42
43 -- | Get the current POSIX time from the system clock.
44 getPOSIXTime :: IO POSIXTime
45 getPOSIXTime = fmap systemToPOSIXTime getSystemTime
46
47 -- | Get the current 'UTCTime' from the system clock.
48 getCurrentTime :: IO UTCTime
49 getCurrentTime = systemToUTCTime `fmap` getSystemTime