Search code examples
javascriptdate-fns

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


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?


Solution

  • 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.