The @perfective/common/date package provides functions to work with the
Date type.
There are a couple important differences in how @perfective handles the Date values.
-
@perfectivetreatsDateobjects as immutable, so setter methods are not supported. -
@perfectivefunctions returnnullinstead of theInvalid Dateinstances.Using
nullallows to combine the results of the functions usingMaybe:import { date, Timestamp, timestamp } from '@perfective/common/date`; import { Maybe, just } from '@perfective/common/maybe'; function parseTime(input: string): Maybe<number> { // (1) const time = Date.parse(input); if (Number.isNaN(time)) { return nothing(); } return just(time); } function maybeTime(input: string): Maybe<Timestamp> { // (2) return just(input).to(date).to(timestamp); }
-
Date.parse(input)returns anumberorNaN, so additional checks are required. -
date()function returnsDate | null, so it’s easily chained intoMaybe.
-
-
Constructors:
-
date(date: Date): Date | null;— creates a copy of a givendate. If the givendateisInvalid Date, returnsnull. -
date(timestamp: Timestamp): Date | null— creates aDatefor a givenTimestamp. If the givenTimestampis invalid, returnsnull. -
date(input: string): Date | null— parses aDatefrom a given inputstring. If the given input cannot be parsed, returnsnull. -
now(): Date— creates aDatefor the current moment. UsesDate.now(), so it can be mocked in the tests (for example, in Jest). -
epoch(): Date— creates aDatefor the Unix epoch (i.e.,January 1, 1970, 00:00:00 UTC).
-
-
Predicates:
-
isValid(date: Date): boolean— returnstrueif a givenDateis a valid (not anInvalid Date). -
isInvalid(date: Date): boolean— returnstrueif a givenDateis anInvalid Date.
-
-
Timestamp = number— an alias type fornumberand is specified in milliseconds since the Unix epoch. -
timestamp(date: Date): Timestamp | null— returns aTimestampfor a given date. If the givenDateisInvalid Date, returnsnull. -
timestamp(input: string): Timestamp | null— parses a given date/timeinputstring as aTimestamp. If the giveninputis invalid, returnsnull.Use instead of the
Date.parse()function, as it’s easy to compose usingmaybe().