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...
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...
Share Improve this question asked Jan 29, 2020 at 7:22 JozefSJozefS 4484 silver badges12 bronze badges3 Answers
Reset to default 12Well, reading date-fns source code answered my question:
import { enGB } from 'date-fns/locale';
let formatString = enGB.formatLong.date({width:"short"});
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
You can use Intl
object of javascript with DateTimeFormat
:
let date = new Intl.DateTimeFormat(navigator.language).format(new Date());
console.log(date)