Skip to content
On this page

Localizing date and time

Fluent has build-in function for formatting date and time: DATETIME. It uses Intl.DateTimeFormat under the hood.

Example:

ftl
today-is = Today is { DATETIME($date, month: "long", year: "numeric", day: "numeric") }

Parameters:

Here is the list of most commonly used parameters:

dateStyle: [ 'full', 'long', 'medium', 'short' ]
timeStyle: [ 'full', 'long', 'medium', 'short' ]
month: [ 'numeric', '2-digit', 'long', 'short', 'narrow' ]
year: [ 'numeric', '2-digit' ]
weekday: [ 'long', 'short', 'narrow' ]
day, hour, minute and second: [ 'numeric', '2-digit' ]

See the Intl.DateTimeFormat for the rest of the parameters and their description.

Example component

vue
<template>
  <p class="demo">
    {{ $t('default', { now }) }}<br>
    {{ $t('today', { now }) }}<br>
    {{ $t('now', { now }) }}
  </p>
</template>

<fluent locale="en">
default = Current date: {{ $now }}
today = Today is {{ DATETIME($now, day: "numeric", month: "long", year: "numeric") }}
now = It is {{ DATETIME($now, hour: "numeric", minute: "numeric", second: "numeric") }}
</fluent>

Output

Current date: ⁨1/27/2023⁩
Today is ⁨January 27, 2023⁩
It is ⁨1:07:26 PM⁩

Using custom library for date formatting

You can add a custom function for date or time formatting instead of using the built-in one.

For example you can use date-fns:

Add custom function to the bundle

ts
import { format } from 'date-fns'

const bundle = new FluentBundle('en', {
  functions: {
    DATEFNS (positionalArgs, namedArgs) {
      const [date, formatString] = positionalArgs as [string, string]
      return format(new Date(date), formatString)
    }
  }
})

const fluent = createFluentVue({
  bundles: [bundle],
})

Use it

vue
<template>
  <p class="demo">
    {{ $t('default', { now }) }}<br>
    {{ $t('today', { now }) }}<br>
    {{ $t('now', { now }) }}
  </p>
</template>

<fluent locale="en">
default = Current date: {{ $now }}
today = Today is {{ DATEFNS($now, "PP") }}
now = It is {{ DATEFNS($now, "pp") }}
</fluent>

Output

Current date: ⁨1/27/2023⁩
Today is ⁨Jan 27, 2023⁩
It is ⁨1:07:26 PM⁩

MIT Licensed