PageRenderTime 20ms CodeModel.GetById 17ms app.highlight 2ms RepoModel.GetById 0ms app.codeStats 0ms

/Data/Time/Clock/POSIX.hs

http://github.com/takano-akio/time
Haskell | 66 lines | 38 code | 15 blank | 13 comment | 0 complexity | 75b1c9fdf2a91aec17deb05f034433bb MD5 | raw file
Possible License(s): BSD-3-Clause
 1-- | POSIX time, if you need to deal with timestamps and the like.
 2-- Most people won't need this module.
 3module Data.Time.Clock.POSIX
 4(
 5	posixDayLength,POSIXTime,posixSecondsToUTCTime,utcTimeToPOSIXSeconds,getPOSIXTime
 6) where
 7
 8import Data.Time.Clock.UTC
 9import Data.Time.Calendar.Days
10import Data.Fixed
11import Control.Monad
12
13#ifdef mingw32_HOST_OS
14import Data.Word	( Word64)
15import System.Win32.Time
16#else
17import Data.Time.Clock.CTimeval
18#endif
19
20-- | 86400 nominal seconds in every day
21posixDayLength :: NominalDiffTime
22posixDayLength = 86400
23
24-- | POSIX time is the nominal time since 1970-01-01 00:00 UTC
25-- 
26-- To convert from a 'Foreign.C.CTime' or 'System.Posix.EpochTime', use 'realToFrac'.
27--
28type POSIXTime = NominalDiffTime
29
30unixEpochDay :: Day
31unixEpochDay = ModifiedJulianDay 40587
32
33posixSecondsToUTCTime :: POSIXTime -> UTCTime
34posixSecondsToUTCTime i = let
35	(d,t) = divMod' i posixDayLength
36 in UTCTime (addDays d unixEpochDay) (realToFrac t)
37
38utcTimeToPOSIXSeconds :: UTCTime -> POSIXTime
39utcTimeToPOSIXSeconds (UTCTime d t) =
40 (fromIntegral (diffDays d unixEpochDay) * posixDayLength) + min posixDayLength (diffToNominal t)
41
42-- | Get the current POSIX time from the system clock.
43getPOSIXTime :: IO POSIXTime
44
45#ifdef mingw32_HOST_OS
46-- On Windows, the equlvalent of POSIX time is "file time", defined as
47-- the number of 100-nanosecond intervals that have elapsed since
48-- 12:00 A.M. January 1, 1601 (UTC).  We can convert this into a POSIX
49-- time by adjusting the offset to be relative to the POSIX epoch.
50
51getPOSIXTime = do
52  FILETIME ft <- System.Win32.Time.getSystemTimeAsFileTime
53  return (fromIntegral (ft - win32_epoch_adjust) / 10000000)
54
55win32_epoch_adjust :: Word64
56win32_epoch_adjust = 116444736000000000
57
58#else
59
60-- Use POSIX time
61ctimevalToPosixSeconds :: CTimeval -> POSIXTime
62ctimevalToPosixSeconds (MkCTimeval s mus) = (fromIntegral s) + (fromIntegral mus) / 1000000
63
64getPOSIXTime = liftM ctimevalToPosixSeconds getCTimeval
65
66#endif