Skip to content

Add helpers to go from Instants to a duration #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 10, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions src/Data/DateTime/Instant.purs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module Data.DateTime.Instant
( Instant
( duration
, durationMillis
, Instant
, instant
, unInstant
, fromDateTime
Expand All @@ -13,8 +15,7 @@ import Data.DateTime (Millisecond, Second, Minute, Hour, Day, Year, DateTime(..)
import Data.Enum (fromEnum, toEnum)
import Data.Function.Uncurried (Fn7, runFn7)
import Data.Maybe (Maybe(..), fromJust)
import Data.Time.Duration (Milliseconds(..))

import Data.Time.Duration (class Duration, Milliseconds(..), negateDuration, toDuration)
import Partial.Unsafe (unsafePartial)

-- | An instant is a duration in milliseconds relative to the Unix epoch
Expand Down Expand Up @@ -74,3 +75,32 @@ toDateTime = toDateTimeImpl mkDateTime
-- TODO: these could (and probably should) be implemented in PS
foreign import fromDateTimeImpl :: Fn7 Year Int Day Hour Minute Second Millisecond Instant
foreign import toDateTimeImpl :: (Year -> Int -> Day -> Hour -> Minute -> Second -> Millisecond -> DateTime) -> Instant -> DateTime

-- | Get the amount of milliseconds between start and end
-- | for example:
-- | ```
-- | do
-- | start <- Instant.now
-- | aLongRunningEffect
-- | end <- Instant.now
-- | let millis = duration end start
-- | log ("A long running effect took " <> show millis)
-- | ```
durationMillis :: { start :: Instant, end :: Instant } → Milliseconds
durationMillis { start, end } =
unInstant end <> negateDuration (unInstant start)

-- | Get the duration between start and end
-- | for example:
-- | ```
-- | do
-- | start <- Instant.now # liftEffect
-- | aLongRunningAff
-- | end <- Instant.now # liftEffect
-- | let
-- | hours :: Hours
-- | hours = duration end start
-- | log ("A long running Aff took " <> show hours)
-- | ```
duration :: forall d. Duration d => { start :: Instant, end :: Instant } → d
duration = durationMillis >>> toDuration