Skip to main content
Home

A library for plain-datetime with type-safe timezone support

This package works with Node.js, DenoIt is unknown whether this package works with Cloudflare Workers, Bun, Browsers
It is unknown whether this package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
It is unknown whether this package works with Bun
It is unknown whether this package works with Browsers
JSR Score
70%
Published
9 months ago (1.0.0)
import type { TimeZone } from "./timezone.ts"; import { Temporal } from "npm:@js-temporal/polyfill@^0.4.4"; export class Time { constructor(private tz: TimeZone) {} from(date: string | Date): Temporal.PlainDateTime { const currTime = this.now().toString().split("T").at(-1); const convertToDate = (dateString: string): Date => { if (dateString.includes("T")) { return new Date(dateString); } return new Date(`${dateString}T${currTime}`); }; let value: Date | undefined; if (date instanceof Date) { const dateString = date.toISOString(); if (dateString.includes("T")) { if (dateString.split("T").at(-1)?.includes("00:00:00")) { value = convertToDate(`${dateString.split("T")[0]}T${currTime}`); } else { value = new Date(`${dateString}`); } } } else { value = convertToDate(date); } if (!value) { throw new Error(); } const epochMilliseconds = value.getTime(); const instant = Temporal.Instant.fromEpochMilliseconds(epochMilliseconds); return new Temporal.ZonedDateTime(instant.epochNanoseconds, this.tz) .toPlainDateTime(); } now(): Temporal.PlainDateTime { const instant = Temporal.Now.instant(); return new Temporal.ZonedDateTime(instant.epochNanoseconds, this.tz) .toPlainDateTime(); } add({ hours, minutes, seconds, }: Partial<{ hours: number; minutes: number; seconds: number; }>): Temporal.PlainDateTime { const duration = Temporal.Duration.from({ hours: hours ?? 0, minutes: minutes ?? 0, seconds: seconds ?? 0, }); return this.now().add(duration); } sub({ hours, minutes, seconds, }: Partial<{ hours: number; minutes: number; seconds: number; }>): Temporal.PlainDateTime { const duration = Temporal.Duration.from({ hours: hours ?? 0, minutes: minutes ?? 0, seconds: seconds ?? 0, }); return this.now().subtract(duration); } comp(a: Temporal.PlainDateTime, b: Temporal.PlainDateTime): 0 | 1 | -1 { switch (Temporal.PlainDateTime.compare(a, b)) { case 0: return 0; case 1: return 1; case -1: return -1; } } }