简体   繁体   中英

date-fns - is there a way to get short date format string

I'm using date-fns and trying to figure out how to get date format string from locales. Eg 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...

Well, 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM