DateTime operations
DateTime operations
Extracting a Date and a Time out of a DateTime
A Date and a Time can be extracted out of a DateTime by deconstructing via pattern matching:
let (DateTime myDate myTime) = myDateTime
We can also use date and time:
date :: DateTime -> Date
time :: DateTime -> Time
Adjusting a DateTime
It’s possible to alter a DateTime directly by using modifyDate, modifyTime, modifyDateF and modifyTimeF:
modifyDate :: (Date -> Date) -> DateTime -> DateTime
modifyTime :: (Time -> Time) -> DateTime -> DateTime
modifyDateF :: forall f. Functor f => (Date -> f Date) -> DateTime -> f DateTime
modifyTimeF :: forall f. Functor f => (Time -> f Time) -> DateTime -> f DateTime
All these functions take as the first argument a function that modifies the specific DateTime
component, a
DateTime
and return the new value.
The latter two are convenience functions which let us work with
modifying functions that produce a Functor.
This is very useful, for example, in conjunction with the adjust function which produces a
Maybe
(which is a Functor
!).
For example:
addThreeDays :: Date -> Maybe Date
addThreeDays = adjust (Days 3.0)
oldDateTime :: DateTime
newDateTime :: Maybe DateTime
newDateTime = modifyDateF addThreeDays oldDateTime
It’s also possible to use adjust directly:
adjust :: forall d. Duration d => d -> DateTime -> Maybe DateTime
This function adjusts a DateTime
value with a Duration offset.
Nothing is returned if the resulting date would be outside
the range of valid dates.
Difference between two DateTime values
To calculate the difference between two DateTimes we can use diff:
diff :: forall d. Duration d => DateTime -> DateTime -> d
The result of diff
is one of the types (Days,
Hours, Minute,
Seconds, Milliseconds) which implements the
Duration type class. We need to help the compiler
by specifying the type when it’s not clear from the context.
daysDiff :: Days
daysDiff = diff date1 date2
hoursDiff :: Hours
hoursDiff = diff date1 date2