Localizing date and time
Fluent has build-in function for formatting date and time: DATETIME
. It uses Intl.DateTimeFormat under the hood.
Example:
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
<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
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
<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