4

I'm using date-fns and trying to figure out how to get date format string from locales. E.g. when using en-US locale I'd like to get 'MM/dd/yyyy' as the result.

I found this answer Get Locale Short Date Format using javascript but it seems redundant to write own function for that as date-fns locales already contain such string...

JozefS
  • 328
  • 2
  • 11

3 Answers3

10

Well, reading date-fns source code answered my question:

import { enGB } from 'date-fns/locale';
let formatString = enGB.formatLong.date({width:"short"});
JozefS
  • 328
  • 2
  • 11
2

You can use Intl object of javascript with DateTimeFormat:

let date = new Intl.DateTimeFormat(navigator.language).format(new Date());

console.log(date)
Jai
  • 74,255
  • 12
  • 74
  • 103
2
var dateFns = require("date-fns")
var locale = require("date-fns/locale")

dateFns.format(new Date(), 'P', { locale: locale.enGB }) // 29/01/2020
dateFns.format(new Date(), 'P', { locale: locale.en })   // 01/29/2020

You will still need to create a mapping from locale string to date-fns locale modules as recommended by their documentation https://date-fns.org/v1.9.0/docs/I18n

Alexander
  • 397
  • 1
  • 8