最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 12

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)

发布评论

评论列表(0)

  1. 暂无评论