summaryrefslogtreecommitdiff
path: root/src/Utils/Time.hs
blob: 2139c53da746d1d752c034e247fb4136facb71e3 (plain)
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
{-|
Module      : Utils.Time
Copyright   : (c) UU, 2019
License     : MIT
Maintainer  : Tom Smeding
Stability   : experimental
Portability : POSIX, macOS, Windows
-}
module Utils.Time where

import Data.Time.Clock
import Data.Time.Clock.System hiding (getSystemTime)
import qualified Data.Time.Clock.System as Sys
import Data.Time.Format


-- | A timestamp in milliseconds.
newtype TimeStamp = TimeStamp Int
  deriving (Show, Read, Eq, Ord)

-- | The number of milliseconds stored in the timestamp newtype.
timestampMS :: TimeStamp -> Int
timestampMS (TimeStamp n) = n

-- | Offset the timestamp by the given number of milliseconds.
plusMS :: TimeStamp -> Int -> TimeStamp
plusMS (TimeStamp n) m = TimeStamp (n + m)

-- | The number of milliseconds that the first timestamp is later than the
-- second.
subtractMS :: TimeStamp -> TimeStamp -> Int
subtractMS (TimeStamp n) (TimeStamp m) = n - m

-- | Return the current system time as a timestamp.
getSystemTime :: IO TimeStamp
getSystemTime = TimeStamp . systemToMS <$> Sys.getSystemTime
  where
    systemToMS tm = let MkSystemTime s ns = truncateSystemTimeLeapSecond tm
                    in fromIntegral s * 1000 + fromIntegral ns `div` 1000000

-- | Show a UTCTime in ISO-8601 format.
iso8601Show :: UTCTime -> String
iso8601Show = formatTime defaultTimeLocale (iso8601DateFormat (Just "%H:%M:%S"))