date-fns: how to define a default locale app-wide?
Asked Answered
B

2

11

It's pretty straightforward to set a locale in a per-function call basis:

import { formatRelative, subDays } from 'date-fns'
import { ptBR } from 'date-fns/locale'

formatRelative(subDays(new Date(), 3), new Date(), { locale: ptBR })

But how do I set a default locale to be used app-wide?

Brasil answered 16/6, 2021 at 12:23 Comment(0)
I
5

As I know, there is no such option. Usually I create custom wrapper function around formatDate functions and pass there application locale. You could store locale in global variables or in app level stores:

formatRelativeWrap.js

import { formatRelative } from 'date-fns'
import AppStore from 'appStore'

export default (date1, date2, locale) => {
    return formatRelative(date1, date2, { locale: locale || AppStore.defaultLocale})
}

As @Pointy mentioned there is note about this in official docs - https://date-fns.org/v2.22.1/docs/I18n - second example.

Insolent answered 16/6, 2021 at 12:34 Comment(2)
This is in the date-fns documentation, complete with example code.Ressieressler
(I meant that comment supportively, if that's not clear.)Ressieressler
C
19

This has been released in version 2.29: https://date-fns.org/v2.29.0/docs/setDefaultOptions

// Set global locale:
var setDefaultOptions = require('date-fns/setDefaultOptions')
import { es } from 'date-fns/locale'
setDefaultOptions({ locale: es })
Cadence answered 18/10, 2022 at 9:59 Comment(0)
I
5

As I know, there is no such option. Usually I create custom wrapper function around formatDate functions and pass there application locale. You could store locale in global variables or in app level stores:

formatRelativeWrap.js

import { formatRelative } from 'date-fns'
import AppStore from 'appStore'

export default (date1, date2, locale) => {
    return formatRelative(date1, date2, { locale: locale || AppStore.defaultLocale})
}

As @Pointy mentioned there is note about this in official docs - https://date-fns.org/v2.22.1/docs/I18n - second example.

Insolent answered 16/6, 2021 at 12:34 Comment(2)
This is in the date-fns documentation, complete with example code.Ressieressler
(I meant that comment supportively, if that's not clear.)Ressieressler

© 2022 - 2024 — McMap. All rights reserved.