Title here
Summary here
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Data.DateTime (DateTime, Year(..), Month(..), Day(..), Hour(..), Minute(..), Second(..), Millisecond(..), adjust)
import Data.DateTime.Instant (Instant, unInstant, toDateTime)
import Data.Time.Duration (Milliseconds(..), Days(..), negateDuration)
import Data.Enum (toEnum)
import Data.Maybe (fromMaybe)
import Effect.Now (now)
main :: Effect Unit
main = do
-- We'll start by getting the current time.
nowInstant <- now
log $ show $ toDateTime nowInstant
-- You can build a DateTime by providing the year, month, day, etc.
let then' = fromMaybe bottom $
DateTime <$> toEnum 2009
<*> pure November
<*> toEnum 17
<*> toEnum 20
<*> toEnum 34
<*> toEnum 58
<*> toEnum 651
log $ show then'
-- You can extract the various components of the DateTime value as expected.
log $ show $ (\(Year y) -> y) $ year then'
log $ show $ month then'
log $ show $ (\(Day d) -> d) $ day then'
log $ show $ (\(Hour h) -> h) $ hour then'
log $ show $ (\(Minute m) -> m) $ minute then'
log $ show $ (\(Second s) -> s) $ second then'
log $ show $ (\(Millisecond ms) -> ms) $ millisecond then'
-- The day of the week is also available.
log $ show $ weekday then'
-- These functions compare two DateTimes, testing if the
-- first occurs before, after, or at the same time
-- as the second, respectively.
log $ show $ then' < toDateTime nowInstant
log $ show $ then' > toDateTime nowInstant
log $ show $ then' == toDateTime nowInstant
-- We can compute the duration between two DateTimes.
let diff = unInstant nowInstant - unInstant (fromMaybe bottom $ toInstant then')
log $ show diff
-- We can compute the length of the duration in various units.
log $ show $ diff / 3600000.0 -- hours
log $ show $ diff / 60000.0 -- minutes
log $ show $ diff / 1000.0 -- seconds
log $ show diff -- milliseconds
-- You can use `adjust` to advance a DateTime by a given
-- duration, or with a negative duration to move backwards.
log $ show $ adjust (Milliseconds diff) then'
log $ show $ adjust (Milliseconds (-diff)) then'
This PureScript code demonstrates working with dates and times. Here’s a breakdown of the translation:
Data.DateTime
and related modules for date and time operations.time.Now()
function is replaced with Effect.Now.now
.DateTime
constructor with toEnum
for each component.DateTime
is done using functions like year
, month
, day
, etc.DateTime
values are done using standard comparison operators.Add
method is replaced with the adjust
function.Note that PureScript’s type system and functional nature lead to some differences in how we handle potential errors (using Maybe
) and how we extract values from newtypes (using pattern matching).
To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js, assuming you have the necessary dependencies installed.
$ pulp run
This will compile the PureScript code and run the resulting JavaScript.