File: POSIX.hs

package info (click to toggle)
ghc 9.6.6-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 158,216 kB
  • sloc: haskell: 648,228; ansic: 81,656; cpp: 11,808; javascript: 8,444; sh: 5,831; fortran: 3,527; python: 3,277; asm: 2,523; makefile: 2,298; yacc: 1,570; lisp: 532; xml: 196; perl: 145; csh: 2
file content (54 lines) | stat: -rw-r--r-- 1,647 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
{-# LANGUAGE Safe #-}

-- | POSIX time, if you need to deal with timestamps and the like.
-- Most people won't need this module.
--
-- You can use 'POSIXTime' to obtain integer/word timestamps. For example:
--
-- > import Data.Time
-- > import Data.Time.Clock.POSIX
-- > import Data.Int
-- >
-- > nanosSinceEpoch :: UTCTime -> Int64
-- > nanosSinceEpoch =
-- >     floor . (1e9 *) . nominalDiffTimeToSeconds . utcTimeToPOSIXSeconds
-- >
-- > main :: IO ()
-- > main = do
-- >     u <- getCurrentTime
-- >     print $ nanosSinceEpoch u
module Data.Time.Clock.POSIX (
    posixDayLength,
    POSIXTime,
    posixSecondsToUTCTime,
    utcTimeToPOSIXSeconds,
    getPOSIXTime,
    getCurrentTime,
    systemToPOSIXTime,
) where

import Data.Fixed
import Data.Time.Calendar.Days
import Data.Time.Clock.Internal.POSIXTime
import Data.Time.Clock.Internal.UTCTime
import Data.Time.Clock.System

posixSecondsToUTCTime :: POSIXTime -> UTCTime
posixSecondsToUTCTime i = let
    (d, t) = divMod' i posixDayLength
    in UTCTime (addDays d systemEpochDay) (realToFrac t)

utcTimeToPOSIXSeconds :: UTCTime -> POSIXTime
utcTimeToPOSIXSeconds (UTCTime d t) =
    (fromInteger (diffDays d systemEpochDay) * posixDayLength) + min posixDayLength (realToFrac t)

systemToPOSIXTime :: SystemTime -> POSIXTime
systemToPOSIXTime (MkSystemTime s ns) = (fromIntegral s) + (fromIntegral ns) * 1E-9

-- | Get the current POSIX time from the system clock.
getPOSIXTime :: IO POSIXTime
getPOSIXTime = fmap systemToPOSIXTime getSystemTime

-- | Get the current 'UTCTime' from the system clock.
getCurrentTime :: IO UTCTime
getCurrentTime = systemToUTCTime `fmap` getSystemTime