Use the original Rust Jiff datetime library from JavaScript. Jiff 1.0.0 runs as precompiled WebAssembly with its IANA time-zone database bundled. Consumers do not need Rust. Jiff is the only datetime engine. There is no Temporal or polyfill dependency, and the package does not modify globals. This independent package exposes a documented subset of Jiff. Requires Node.js 20 or later. After publication, install with npm install jiff-js. For this checkout, build and install the tarball as described below. import { Timestamp, Span } from 'jiff-js'; const start = Timestamp.from('2024-07-11T01:14:00Z'); const end = start.inTz('America/New_York') .add(Span.new().months(1).hours(2)); console.log(end.toString()); // 2024-08-10T23:14:00-04:00[America/New_York] console.log(end.timestamp().toString()); // 2024-08-11T03:14:00Z CommonJS uses the same API and loads WASM automatically: const { Timestamp } = require('jiff-js'); console.log(Timestamp.now().inTz('UTC').toString()); Browsers Use the web entry with a bundler, initializing before creating values: import init, { Timestamp } from 'jiff-js/web'; await init(); console.log(Timestamp.now().inTz('Asia/Tokyo').toString()); The loader fetches WASM relative to the generated module. Your bundler or static server must preserve or emit the asset. The jiff-js/jiff.wasm export identifies the browser binary. When the host manages assets, pass a URL, Response, bytes, or a compiled WebAssembly module: await init('/assets/jiff.wasm'); // Or: await init(wasmBytes); Repeated initialization is safe, and failed initialization can be retried. Calls before initialization throw TypeError. Serve WASM as application/wasm for streaming compilation. The browser security policy must permit WebAssembly and fetching the asset. Modern browsers need WebAssembly, bigint, and Intl. Other runtimes, including edge workers, need separate verification. All values are immutable. Arithmetic returns a new value. Invalid input throws TypeError or RangeError. Integer inputs are checked before crossing into WASM. TypeScript declarations cover the Node and browser entries. Each class has from, toString, toJSON, and equals. The civil namespace provides Date, Time, and DateTime aliases plus date and time constructor helpers. tz.TimeZone aliases TimeZone. Timestamps const t = Timestamp.fromNanosecond(-1n); t.toString(); // '1969-12-31T23:59:59.999999999Z' t.asNanosecond(); // -1n t.asMicrosecond(); // 0n t.asMillisecond(); // 0 Epoch factories fromSecond, fromMillisecond, fromMicrosecond, and fromNanosecond accept bigint or safe integer numbers. asSecond and asMillisecond return numbers; asMicrosecond and asNanosecond return bigint. Conversions truncate toward zero, including before the Unix epoch. Timestamp.now() and ZonedDateTime.now() use the JavaScript clock, which has millisecond resolution. Parsed and computed values retain nanosecond precision. Intl discovers the system zone; Jiff's bundled data supplies all zone rules. Civil values import { CivilDate, CivilTime, CivilDateTime } from 'jiff-js'; const date = new CivilDate(2024, 2, 29); date.at(new CivilTime(12, 30, 0, 123456789)).toString(); // '2024-02-29T12:30:00.123456789' CivilDate.from({ year: 2024, month: 1, day: 31 }) .add({ months: 1 }).toString(); // '2024-02-29' CivilDateTime.from('2024-07-11T12:30').inTz('Europe/Paris'); Numeric constructors accept a full fractional second in their final subsecond argument, in 0..999999999. Field records use separate millisecond, microsecond, and nanosecond fields, each in 0..999. Date records require year, month, and day; date-time records combine these with time fields. Civil fields are readonly properties. Weekdays use Monday = 1 through Sunday = 7. Dates compose with at(time) or at(hour, minute, second, subsecond). date.toDateTime(time) and time.toDateTime(date) also compose values. Date-time values expose date() and time(). inTz(zone, options) assigns a zone explicitly to a civil date or date-time. DST and time zones import { ZonedDateTime, CivilDateTime } from 'jiff-js'; const start = ZonedDateTime.from('2024-03-09T12:00-05:00[America/New_York]'); start.add({ days: 1 }).hour; // 12, only 23 elapsed hours later start.add({ hours: 24 }).hour; // 13 const fold = CivilDateTime.from('2024-11-03T01:30'); fold.inTz('America/New_York', { disambiguation: 'earlier' }).offset; // '-04' fold.inTz('America/New_York', { disambiguation: 'later' }).offset; // '-05' Disambiguation accepts compatible, earlier, later, or reject. The default compatible picks the earlier repeated time and moves forward through a gap. reject throws for gaps and repeats. ZonedDateTime.from also accepts this option for offset-free strings. Offset-plus-zone strings reject conflicting offsets. Zoned values expose timestamp(), datetime(), date(), time(), timeZone(), and inTz(zone). Changing zones preserves the instant. TimeZone.from accepts IANA names and Jiff-supported fixed offsets. TimeZone.UTC and TimeZone.system() are conveniences. Offsets use Jiff's concise spelling, such as -04 or +05:30. Spans, differences and rounding const span = Span.new().hours(1).minutes(30); span.total('minute'); // 90 span.negated().toString(); // '-PT1H30M' const start = Timestamp.from('2024-01-01T00:00:00Z'); start.until(start.add(span), { largestUnit: 'hour' }).toString(); // 'PT1H30M' start.add({ seconds: 31 }).round('minute').toString(); // '2024-01-01T00:01:00Z' Spans accept ISO duration strings or records with plural unit names. Read fields with getYears() through getNanoseconds(). Microseconds and nanoseconds accept bigint and their getters return bigint; other fields use safe integer numbers. Mixed signs are rejected. Span equality compares fields, so PT60M and PT1H differ. abs() and negated() preserve fields. Calendar totals require a reference, for example Span.from({ days: 1 }).total({ unit: 'hour', relativeTo: zonedValue }). Totals return floating-point numbers, as in Jiff. Use timestamp nanoseconds for exact elapsed integers. Date/time values support add, subtract, until, since, equals, and static compare. Differences accept largestUnit, smallestUnit, roundingMode, and roundingIncrement. Timestamp, civil time, civil date-time, and zoned values support round(unit) or round({ smallestUnit, roundingMode, roundingIncrement }). Units are singular names from year through nanosecond; Jiff rejects units that do not apply. Rounding defaults to halfExpand; differences truncate. Other modes are ceil, floor, expand, trunc, halfCeil, halfFloor, halfTrunc, and halfEven. Dates reject time units. Civil times reject calendar units and wrap at midnight. Timestamps reject days and larger calendar units; use civil or zoned values. Month-end arithmetic follows Jiff's day-constraining behavior. Timestamp and zoned comparisons compare instants; compare their strings too when zone identity matters. Implicit numeric comparisons throw. JSON.stringify uses each value's string representation. Scope and costs This release exposes the API above, rather than every Rust Jiff API. It omits custom TZif databases, strftime/strptime, localization, non-Gregorian calendars, POSIX time-zone definitions, and Rust-specific integrations. Jiff's numeric ranges and parsing behavior apply. Jiff does not model leap seconds. The string bridge incurs serialization and parsing overhead. No manual WASM allocation disposal is needed. No performance advantage over JavaScript libraries is claimed. Each WASM binary is approximately 708 KiB before compression; the tarball contains separate Node and browser binaries. Time-zone updates require a new package build and release. Build and verify Building requires Rust 1.85 or later and the matching wasm-bindgen CLI. Consumers of the tarball need neither. rustup target add wasm32-unknown-unknown cargo install wasm-bindgen-cli --version 0.2.121 --locked npm ci npm run build npm run check npm run test:browser npm run test:package npm pack For browser tests, run npx playwright install chromium or set JIFF_CHROMIUM_EXECUTABLE to an installed Chromium executable. npm pack rebuilds and creates jiff-js-0.1.0.tgz. Install that file in another project with npm install ./jiff-js-0.1.0.tgz. Packing does not publish to npm; the package name has not been reserved. The ignored Rust reference checkout is not needed to build. The Cargo dependency and lockfile provide the engine. The wrapper and bindings use MIT. Bundled dependencies retain their licenses under dist/licenses; see NOTICE.
AI NEWS JOURNAL
Hacker News Show HNAI NEWS / JOURNAL
Show HN: I built a JavaScript library on Rust's amazing Jiff via WebAssembly
Article URL: https://github.com/skorotkiewicz/jiff-js Comments URL: https://news.ycombinator.com/item?id=50529532 Points: 1 # Comments: 0
翻訳サービスが停止中のため原文を表示しています。