Link Search Menu Expand Document

getDateFormatterSource() function

Returns a string of JavaScript source that evaluates to a date formatter function with the same (date: Date | number) => string signature as the function returned by getDateFormatter().

Signature:

export declare function getDateFormatterSource(locales: string | string[], tokens: string | DateToken[], onError?: (err: DateFormatError) => void): string;

Parameters

Parameter Type Description
locales string | string[] One or more valid BCP 47 language tags, e.g. fr or en-CA
tokens string | DateToken[] An ICU DateFormat skeleton string, or an array or parsed DateToken tokens
onError (err: DateFormatError) => void If defined, will be called separately for each encountered parsing error and unsupported feature.

Returns:

string

Remarks

The returned function will memoize an Intl.DateTimeFormat instance.

Example

import { getDateFormatterSource } from '@messageformat/date-skeleton'

getDateFormatterSource('en-CA', 'GrMMMdd', console.error)
// '(function() {\n' +
// '  var opt = {"era":"short","calendar":"gregory","year":"numeric",' +
//      '"month":"short","day":"2-digit"};\n' +
// '  var dtf = new Intl.DateTimeFormat("en-CA", opt);\n' +
// '  return function(value) { return dtf.format(value); }\n' +
// '})()'

const src = getDateFormatterSource('en-CA', 'hamszzzz', console.error)
// '(function() {\n' +
// '  var opt = {"hour":"numeric","hourCycle":"h12","minute":"numeric",' +
//      '"second":"numeric","timeZoneName":"long"};\n' +
// '  var dtf = new Intl.DateTimeFormat("en-CA", opt);\n' +
// '  return function(value) { return dtf.format(value); }\n' +
// '})()'

const fmt = new Function(`return ${src}`)()
const date = new Date(2006, 0, 2, 15, 4, 5, 789)
fmt(date) // '3:04:05 p.m. Newfoundland Daylight Time'