Time Formatting Parsing in PureScript
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Data.DateTime (DateTime, adjust)
import Data.Time.Duration (Minutes(..))
import Data.Maybe (fromMaybe)
import Data.Formatter.DateTime (formatDateTime, unformat)
import Data.Either (Either(..))
main :: Effect Unit
main = do
now <- getCurrentDateTime
-- Here's a basic example of formatting a time
-- according to ISO8601, which is similar to RFC3339
log $ formatDateTime "YYYY-MM-DDTHH:mm:ssZ" now
-- Time parsing uses the same format strings as formatting
case unformat "YYYY-MM-DDTHH:mm:ssZ" "2012-11-01T22:08:41+00:00" of
Right parsed -> log $ show parsed
Left err -> log $ show err
-- Format using custom layouts
log $ formatDateTime "h:mm A" now
log $ formatDateTime "ddd MMM DD HH:mm:ss YYYY" now
log $ formatDateTime "YYYY-MM-DDTHH:mm:ss.SSSZ" now
-- Parse using a custom format
case unformat "h mm A" "8 41 PM" of
Right parsed -> log $ show parsed
Left err -> log $ show err
-- For purely numeric representations you can also
-- use standard string formatting with the extracted
-- components of the time value
log $ formatDateTime "YYYY-MM-DDTHH:mm:ss-00:00" now
-- Parsing will return an error on malformed input
case unformat "ddd MMM DD HH:mm:ss YYYY" "8:41PM" of
Right _ -> log "Parsed successfully"
Left err -> log $ "Error: " <> show err
-- Helper function to get current date time
getCurrentDateTime :: Effect DateTime
getCurrentDateTime = do
now <- now
pure $ fromMaybe now $ adjust (Minutes 0.0) now
In PureScript, we use the purescript-formatters
library for date and time formatting and parsing. This library provides similar functionality to Go’s time package, but with a slightly different API.
Here are some key differences and explanations:
PureScript uses
Effect
for side effects, similar to Go’sfunc main()
.Instead of
time.Now()
, we use a helper functiongetCurrentDateTime
that returns the current time.The
formatDateTime
function is used for formatting dates, similar to Go’sFormat
method.For parsing, we use the
unformat
function, which returns anEither
type to handle potential errors.PureScript doesn’t have built-in constants for date formats like
RFC3339
, so we use string patterns directly.The date-time patterns in PureScript are slightly different from Go. For example,
YYYY
for year,MM
for month,DD
for day, etc.Error handling in PureScript is typically done using the
Either
type, which we pattern match on to handle success and error cases.PureScript doesn’t have a direct equivalent to Go’s string formatting with
Printf
. Instead, we use theformatDateTime
function with a custom format string to achieve similar results.
This example demonstrates how to perform time formatting and parsing in PureScript, covering the main concepts from the original example while adapting to PureScript’s functional paradigm and type system.