moment vs date-fns语言环境日期格式 [英] moment vs date-fns locale date formats

查看:560
本文介绍了moment vs date-fns语言环境日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我们的应用程序上下文中评估DateFns和Moment,发现DateFns中似乎有一个重要的遗漏.

I'm evaluating DateFns and Moment in the context of our app, and found what appears to be an important omission in DateFns.

在Moment中,语言环境支持使您可以格式化日期或时间的语言环境正确的表示形式.例如,日期格式"LL"和"L"将为英语语言环境生成以下内容:

In Moment, locale support allows you to format locale-correct representations of a date or time. For instance, the date formats "LL" and "L" will produce the following for the English locale:

November 27, 2017
11/27/2017

以下为西班牙语言环境:

And the following for the Spanish locale:

27 de noviembre de 2017
27/11/2017

尤其要注意的是,在第二个示例中,月份在英语之前在一天之前,而一天在西班牙语之前在月份之前.这正是您希望语言环境代码为您处理的事情.这是语言环境在几乎所有日期时间库(C ++,C#,Java,Python等)中的工作方式.

Note in particular that in the second example, the month comes before the day in English, whereas the day comes before the month in Spanish. That's exactly the kind of thing you want locale code to handle for you. This is how locales work in almost all datetime libraries (C++, C#, Java, Python, etc.)

在DateFns中,似乎没有用于区域设置正确的格式选项长日期,短日期,时间等.他们提供的使用语言环境的示例要求您将特定于语言环境的格式字符串传递给它:

In the DateFns, there doesn't appear to be a format option for locale-correct long date, short date, time, etc.. The example they give for using a locale requires that you pass it the locale-specific format string:

// Represent 2 July 2014 in Esperanto:
var eoLocale = require('date-fns/locale/eo')
var result = format(
  new Date(2014, 6, 2),
  'Do [de] MMMM YYYY',
  {locale: eoLocale}
)

换句话说,我需要知道我支持的每个语言环境的日期/时间格式,这与首先获得语言环境支持的目的是对立的.]

In other words, I need to know the date/time format for every locale I support, which defeats the purpose of having locale support in the first place.]

我可以使用Javascript的toLocaleString,但是随后我的应用程序通过两种不同的方式来管理语言环境.

I can use Javascript's toLocaleString, but then my app it managing locale two different ways.

是否有某种方法可以打印出某个特定语言环境的短日期",而无需我告诉DateFns该语言环境的格式是什么?

Is there some way of printing out, say, a "short date" for a particular locale without me telling DateFns what the format for that locale is?

推荐答案

我使用date-fns的esm版本,并且可以使用与moment使用相同的格式:

I use the esm version of date-fns and you can use the same type of formats that moment uses :

import { format } from 'date-fns/esm'
import { enUS, fr } from 'date-fns/esm/locale'

我将语言环境存储在一个对象中:

I'll store the locales in an object :

this.dateLocales = { fr: fr, en: enUS }

并使用以下格式:

LT: 'h:mm aa',
LTS: 'h:mm:ss aa',
L: 'MM/DD/YYYY',
LL: 'MMMM D YYYY',
LLL: 'MMMM D YYYY h:mm aa',
LLLL: 'dddd, MMMM D YYYY h:mm aa'

所以您可以:

format(
  new Date(2014, 6, 2),
  'LL',
  {locale: this.dateLocales.fr}
)

这些格式已本地化

这篇关于moment vs date-fns语言环境日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆