Converting
There are two ways to run a conversion. Both live at the package root.
convert: one-off conversions
convert(format, options) takes the format string and an options object carrying the direction:
import { convert } from 'rosetta-date'
import { ldml, moment } from 'rosetta-date/dialects'
convert('DD/MM/YYYY', { from: moment, to: ldml }) // 'dd/MM/yyyy'
convert('yyyy-MM-dd', { from: ldml, to: moment }) // 'YYYY-MM-DD'Use convert when the source and target vary between calls.
createConverter: fixed direction
When you convert repeatedly in the same direction, bind it once. createConverter(from, to, options?)
returns a plain (format: string) => string:
import { createConverter } from 'rosetta-date'
import { ldml, moment } from 'rosetta-date/dialects'
const toLdml = createConverter(moment, ldml)
toLdml('YYYY-MM-DD') // 'yyyy-MM-dd'
toLdml('hh:mm A') // 'hh:mm a'The returned function can be stored on an object or passed as a callback. Per-dialect compilation is cached, so a bound converter avoids recompiling the dialects on every call.
Options
Both APIs accept the same options (convert merges them into its options object alongside from /
to):
| Option | Type | Default | Purpose |
|---|---|---|---|
onUnsupportedToken | 'literalize' | 'throw' | handler | 'literalize' | What to do when a token has no clean target. See Unsupported tokens. |
import { createConverter } from 'rosetta-date'
import { dayjs, momentjs } from 'rosetta-date/libraries'
const safe = createConverter(momentjs, dayjs, { onUnsupportedToken: 'throw' })The default policy preserves every token and escapes unsupported tokens as literals. Use 'throw'
when validation or a mass migration must report unsupported tokens.
Performance: reuse dialect objects
Per-dialect compilation is cached by object identity, so reuse the same Dialect or Library
instances across calls rather than rebuilding them. The built-in dialects and libraries are shared
objects. If you define your own, see
Validation happens once.