aboutsummaryrefslogtreecommitdiff
path: root/src/lib/haskell/Utils/Time.hs
blob: ce36293cda317c21e64401b17a0a9b7e65f0eef7 (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
module Utils.Time
  ( getCurrentFormattedTime
  , asleepDuration
  , addNoise
  ) where

import           Data.Text           (Text)
import qualified Data.Text           as T
import           Data.Time.Clock     (DiffTime)
import qualified Data.Time.Clock     as Clock
import qualified Data.Time.Format    as Format
import qualified Data.Time.LocalTime as LocalTime
import qualified System.Random       as Random

getCurrentFormattedTime :: IO Text
getCurrentFormattedTime = do
  zonedTime <- LocalTime.getZonedTime
  return (T.pack $ Format.formatTime Format.defaultTimeLocale "%Hh%M" zonedTime)

asleepDuration :: DiffTime -> DiffTime -> DiffTime -> Maybe DiffTime
asleepDuration from to t =
  if t < from && from < to then
    Just $ from - t
  else if t > to && to > from then
    Just $ day - t + from
  else if t > to && t < from then
    Just $ from - t
  else
    Nothing
  where
    day = (realToFrac Clock.nominalDay) :: DiffTime

-- |Add noise to a duration.
-- > t - (n / 2) <= addNoise t n <= t + (n / 2)
addNoise :: DiffTime -> DiffTime -> IO DiffTime
addNoise t n = do
  r <- Random.randomIO :: IO Float
  return $ t + (Clock.secondsToDiffTime . round $ (r * (fromIntegral . toSeconds $ n))) - n / 2

  where
    toSeconds dt = Clock.diffTimeToPicoseconds dt `div` 10^(12 :: Integer)