velt/time: DateTime and Duration
import { DateTime, Duration } from "velt/time". DateTime is a UTC-first instant: epoch
milliseconds in a small struct. Months are 1-12. Local time is opt-in and DST-aware, using
the OS time zone. TZ overrides it: on macOS and Linux any value the C library understands; on
Windows only UTC (UTC, Etc/UTC, GMT, ...) and fixed offsets (Etc/GMT-2 is UTC+2), other
names keep the system zone. Node differs there: it understands region names like
Europe/Berlin, and uses UTC for a name it doesn't recognise (a typo, the wrong case).
- Constructors:
DateTime.now(),fromEpochMs(ms)utc(year, month, day = 1, hour = 0, minute = 0, second = 0, ms = 0): fields roll over likeDate.UTCparse(s): ISO 8601 / RFC 3339; see the notes for what it acceptsparseHttpDate(s): accepts all three RFC 7231 formatsparseandparseHttpDatethrowDateTimeError.
- UTC getters:
year month day hour minute second millisecond dayOfWeek (0 = Sunday) dayOfYear. parts()/localParts(): DateParts, a struct of all fields plusoffsetMinutes.localOffsetMinutes.- Output:
toISOString():2024-02-29T12:34:56.000ZtoLocalISOString():…+01:00toUTCString(): an HTTP dateformat(pattern)/formatLocal(pattern): tokensYYYY YY M MM MMM MMMM D DD DDDD ddd dddd H HH h hh A a m mm s ss SSS Z ZZ; text in[brackets]is literaltoEpochMs(),toEpochSeconds()
- Arithmetic:
addMs addSeconds addMinutes addHours addDaysaddMonthsandaddYears: clamp the day, so Jan 31 + 1 month is Feb 29 in a leap yearadd(Duration),diffMs(other),since(other): Duration,startOfDay()
- Comparison:
compareTo(it implementsComparable, so generic code can use<),isBefore,isAfter,equals. Duration:- constructors:
ofMs ofSeconds ofMinutes ofHours ofDays toMs(),toSeconds(): f64,plus,minus,negated,compareTotoString(): ISO 8601, e.g.P1DT12H
- constructors:
ts
import { DateTime, Duration } from "velt/time";
const d = DateTime.parse("2024-01-31T09:30:00+01:00");
console.log(d.toISOString(), d.format("dddd D MMMM YYYY, HH:mm"));
console.log(d.addMonths(1).toISOString(), d.addDays(1).toUTCString());
const due = d.add(Duration.ofHours(36));
console.log(due.since(d).toString(), due.isAfter(d)); // P1DT12H true
try {
DateTime.parse("2023-02-29");
} catch (e) {
console.log(e.message); // Invalid date: 2023-02-29
}Notes:
parseacceptsYYYY,YYYY-MM,YYYY-MM-DDor±YYYYYYyears, then an optional timeTHH:mm[:ss[.fraction]](tor a space also work), then an optional zoneZ,±HH:mm,±HHmmor±HH.parsereads strings without an offset as UTC (JS reads date-times without one as local time), and it rejects impossible dates and times instead of rolling them over.- There are no leap seconds and no time-zone database beyond the OS offset.