Formatting a date

Introduction

Intl.DateTimeFormat formats a date for a locale, time zone, and calendar. This sheet covers the options, the output parts, and the parsing traps.

Basic usage

const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0))

new Intl.DateTimeFormat().format(date)
// → '12/19/2012'

Examples assume the en-US locale in America/Los_Angeles, so the UTC date above prints as the 19th. Later cards reuse date; format() takes a Date or a timestamp, so build one formatter and reuse it in loops.

See: format()

Locales

const format = (locale) => new Intl.DateTimeFormat(locale, {
  timeZone: 'UTC'
}).format(date)

format('en-US')  // → '12/20/2012'
format('en-GB')  // → '20/12/2012'
format('de-DE')  // → '20.12.2012'
format('ja-JP')  // → '2012/12/20'

Field order, separators, and digits come from CLDR data, so the same Date prints differently per locale. Unsupported tags fall back to the runtime default.

See: locales argument

Locale arrays

new Intl.DateTimeFormat(['xx-YY', 'en-US'], {
  dateStyle: 'long',
  timeZone: 'UTC'
}).format(date)
// → 'December 20, 2012'

The first supported tag wins, so pass the visitor's preferences in order.

See: locale negotiation

Options without a locale

const opts = { dateStyle: 'long', timeZone: 'UTC' }

new Intl.DateTimeFormat('default', opts).format(date)
// → 'December 20, 2012'

new Intl.DateTimeFormat(undefined, opts).format(date)
// → 'December 20, 2012'

'default' and undefined both fall back to the runtime's locale; 'default' is not a special value, it is an unsupported tag that negotiation drops.

See: locales argument

Preset styles

Formatter

const style = (dateStyle, timeStyle) => (
  new Intl.DateTimeFormat('en-US', {
    dateStyle,
    timeStyle,
    timeZone: 'UTC'
  }).format(date)
)

Output

style('full')             // → 'Thursday, December 20, 2012'
style('long')             // → 'December 20, 2012'
style('medium')           // → 'Dec 20, 2012'
style('short')            // → '12/20/12'
style('medium', 'short')  // → 'Dec 20, 2012, 3:00 AM'

dateStyle and timeStyle cover the common shapes; combining either with an individual field option throws a TypeError.

See: dateStyle

Date and time fields

Weekday and month names

const fmt = (options) => new Intl.DateTimeFormat('en-US', {
  timeZone: 'UTC', ...options
}).format(date)

fmt({ weekday: 'long' })   // → 'Thursday'
fmt({ month: 'long' })     // → 'December'
fmt({ month: 'short' })    // → 'Dec'
fmt({ month: 'narrow' })   // → 'D'

Names take 'narrow', 'short', or 'long'; the widths differ per locale.

See: month

Numeric dates

Long form

new Intl.DateTimeFormat('en-US', {
  year: 'numeric', month: 'long', day: 'numeric',
  timeZone: 'UTC'
}).format(date)
// → 'December 20, 2012'

Two-digit

new Intl.DateTimeFormat('en-US', {
  year: '2-digit', month: '2-digit', day: '2-digit',
  timeZone: 'UTC'
}).format(date)
// → '12/20/12'

year takes 'numeric' or '2-digit'; month and day also take a width.

See: year

Time of day

const time = (options) => new Intl.DateTimeFormat('en-US', {
  timeZone: 'UTC', ...options
}).format(date)

time({ hour: 'numeric', minute: '2-digit' })
// → '3:00 AM'

Add second and fractionalSecondDigits for finer output; fields combine freely, but not with timeStyle.

See: hour

12- and 24-hour clocks

Formatter

const midnight = new Date(Date.UTC(2012, 11, 20, 0, 0))
const clock = (hourCycle) => new Intl.DateTimeFormat('en-US', {
  hour: 'numeric', minute: '2-digit', hourCycle, timeZone: 'UTC'
}).format(midnight)

Output

clock('h11')  // → '0:00 AM'
clock('h12')  // → '12:00 AM'
clock('h23')  // → '00:00'
clock('h24')  // → '24:00'

h11 and h12 are 12-hour, h23 and h24 are 24-hour. hour12 overrides hourCycle, and h24 prints midnight as 24:00.

See: hourCycle

Time zones

Format in another zone

new Intl.DateTimeFormat('en-US', {
  dateStyle: 'medium',
  timeStyle: 'short',
  timeZone: 'Asia/Tokyo'
}).format(date)
// → 'Dec 20, 2012, 12:00 PM'

timeZone takes an IANA zone name. The Date itself stays the same; only the displayed wall clock changes.

See: timeZone

Visitor's zone

Intl.DateTimeFormat().resolvedOptions().timeZone
// → 'America/Los_Angeles'

Read once, then pass the result as timeZone wherever output must match a second formatter.

See: resolvedOptions()

Zone names and offsets

const zone = (timeZoneName) => new Intl.DateTimeFormat('en-US', {
  month: 'short', day: 'numeric',
  timeZone: 'Australia/Sydney',
  timeZoneName
}).format(date)

zone('short')        // → 'Dec 20, GMT+11'
zone('longOffset')   // → 'Dec 20, GMT+11:00'
zone('shortGeneric') // → 'Dec 20, Sydney Time'

short uses a local abbreviation when the locale has one and falls back to GMT otherwise; …Offset always prints GMT, and …Generic drops daylight saving.

See: timeZoneName

Available zones

Intl.supportedValuesOf('timeZone').slice(0, 3)
// → ['Africa/Abidjan', 'Africa/Accra',
//    'Africa/Addis_Ababa']

Lists the primary IANA names the runtime knows. V8 leaves out UTC and aliases such as US/Pacific, which timeZone still accepts, so catch the constructor error instead of testing membership.

See: Intl.supportedValuesOf()

Working with output

formatToParts()

const parts = new Intl.DateTimeFormat('en-GB', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  timeZone: 'UTC'
}).formatToParts(date)

parts.map(({ type, value }) => `${type}: ${value}`)
// → ['day: 20', 'literal: /', 'month: 12',
//    'literal: /', 'year: 2012']

Joining every value reproduces format(). Use the parts to style numbers without parsing the string back.

See: formatToParts()

No custom patterns

Locale order

new Intl.DateTimeFormat('en-GB', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  timeZone: 'UTC'
}).format(date)
// → '20/12/2012'

ISO output

date.toISOString()
// → '2012-12-20T03:00:00.000Z'

There are no YYYY-MM-DD pattern tokens. Pick a locale whose order matches, or use toISOString() for machine-readable UTC.

See: DateTimeFormat() constructor

Parsing is separate

Date-only string

new Date('2012-12-20').toLocaleDateString('en-US')
// → '12/19/2012'

With a time

new Date('2012-12-20T00:00:00').toLocaleDateString('en-US')
// → '12/20/2012'

A date-only string parses as UTC midnight, so it can land on the previous day locally. Add a time to parse it in the browser's zone.

See: Date.parse()

toLocaleDateString()

date.toLocaleDateString('en-GB', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  timeZone: 'UTC'
})
// → '20/12/2012'

Shorthand for a one-off formatter. It builds a new one per call, so hoist Intl.DateTimeFormat out of loops.

See: toLocaleDateString()

Options reference

Date options

OptionValues
weekday'narrow', 'short', 'long'
era'narrow', 'short', 'long'
year'numeric', '2-digit'
month'numeric', '2-digit', 'narrow', 'short', 'long'
day'numeric', '2-digit'
dateStyle'full', 'long', 'medium', 'short'

See: DateTimeFormat options

Time options

OptionValues
hour'numeric', '2-digit'
minute'numeric', '2-digit'
second'numeric', '2-digit'
fractionalSecondDigits1 to 3
dayPeriod'narrow', 'short', 'long'
timeStyle'full', 'long', 'medium', 'short'
hour12true, false
hourCycle'h11', 'h12', 'h23', 'h24'
timeZoneName'short', 'long', 'shortOffset', 'longOffset', 'shortGeneric', 'longGeneric'

See: DateTimeFormat options

Locale options

OptionValues
timeZoneIANA name, e.g. 'Asia/Tokyo'
numberingSysteme.g. 'latn', 'arab', 'hanidec'
calendare.g. 'gregory', 'iso8601'
localeMatcher'best fit' (default), 'lookup'
formatMatcher'best fit' (default), 'basic'

See: DateTimeFormat options

Errors

Unknown zone

new Intl.DateTimeFormat('en-US', { timeZone: 'Mars/Olympus' })
// RangeError: Invalid time zone specified: Mars/Olympus

Invalid date

new Intl.DateTimeFormat('en-US').format(new Date('nope'))
// RangeError: Invalid time value

Bad zones throw when the formatter is built; invalid dates throw on format(). Check Number.isNaN(date.getTime()) for untrusted input.

See: Exceptions

Also see

0 Comments for this cheatsheet. Write yours!