Localizing date and time

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

Example:

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

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.DateTimeFormatopen in new window for the rest of the parameters and their description.

Example component

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

<fluent locale="en">
default = Now is {{ $now }}
today = Today is {{ DATETIME($now, day: "numeric", month: "long", year: "numeric") }}
now = It is {{ DATETIME($now, hour: "numeric", minute: "numeric") }}
</fluent>
1
2
3
4
5
6
7
8
9
10
11
12
13

Now is ⁨10/13/2021⁩
Today is ⁨October 13, 2021⁩
It is ⁨10:52 AM⁩

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

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],
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Use it

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

<fluent locale="en">
default = Now is {{ $now }}
today = Today is {{ DATEFNS($now, "PP") }}
now = It is {{ DATEFNS($now, "p") }}
</fluent>
1
2
3
4
5
6
7
8
9
10
11
12
13

Now is ⁨10/13/2021⁩
Today is ⁨Oct 13, 2021⁩
It is ⁨10:52 AM⁩