/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

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