git-annex/Utility/TimeStamp.hs

46 lines
1.1 KiB
Haskell
Raw Normal View History

2018-10-30 03:13:36 +00:00
{- timestamp parsing and formatting
2015-05-10 19:23:38 +00:00
-
- Copyright 2015-2016 Joey Hess <id@joeyh.name>
2015-05-10 19:23:38 +00:00
-
2018-10-30 03:13:36 +00:00
- License: BSD-2-clause
2015-05-10 19:23:38 +00:00
-}
{-# LANGUAGE CPP #-}
2018-10-30 03:13:36 +00:00
module Utility.TimeStamp where
2015-05-10 19:23:38 +00:00
import Utility.PartialPrelude
import Utility.Misc
2015-05-10 19:23:38 +00:00
import Data.Time.Clock.POSIX
import Data.Time
import Data.Ratio
2015-05-10 19:23:38 +00:00
#if ! MIN_VERSION_time(1,5,0)
import System.Locale
#endif
2015-05-10 19:36:58 +00:00
{- Parses how POSIXTime shows itself: "1431286201.113452s"
- Also handles the format with no fractional seconds. -}
2015-05-10 19:23:38 +00:00
parsePOSIXTime :: String -> Maybe POSIXTime
2018-10-30 03:33:56 +00:00
parsePOSIXTime = uncurry parsePOSIXTime' . separate (== '.')
{- Parses the integral and decimal part of a POSIXTime -}
parsePOSIXTime' :: String -> String -> Maybe POSIXTime
parsePOSIXTime' sn sd = do
n <- fromIntegral <$> readi sn
let sd' = takeWhile (/= 's') sd
if null sd'
then return n
else do
d <- readi sd'
let r = d % (10 ^ (length sd'))
return $ if n < 0
then n - fromRational r
else n + fromRational r
where
readi :: String -> Maybe Integer
readi = readish
2015-05-10 19:36:58 +00:00
formatPOSIXTime :: String -> POSIXTime -> String
formatPOSIXTime fmt t = formatTime defaultTimeLocale fmt (posixSecondsToUTCTime t)