使用Moment.js的区域设置和特定日期格式 [英] Locale and specific date format with Moment.js
问题描述
我在我的项目和格式化日期中使用Moment.js如下:
I am using Moment.js in my project and formatting dates as follows:
var locale = window.navigator.userLanguage || window.navigator.language;
moment.locale(locale);
someDate.format("L");
它运作良好但有时我需要显示没有年份的日期。我不能使用类似 someDate.format(MM / DD)
的东西,因为在某些语言中它应该是 someDate.format(DD / MM)
。我需要像 L,LL,LLL
这样的东西,但没有年份。
It works good but sometimes I need show a date without year. I can't use something like someDate.format("MM/DD")
because in some languages it should be someDate.format("DD/MM")
. I need something think like L,LL,LLL
but without year.
我该怎么办?
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY LT',
LLLL : 'dddd, MMMM D, YYYY LT'
推荐答案
好的。这有点糟糕,但你知道它会是。
Okay. This is a little awful, but you knew it was going to be.
首先,你可以访问(例如)的实际格式字符串'L'
:
First, you can access the actual format string for (for instance) 'L'
:
var formatL = moment.localeData().longDateFormat('L');
接下来,您可以通过明智的正则表达式替换来执行一些手术:
Next, you can perform some surgery on it with judicious regex replacement:
var formatYearlessL = formatL.replace(/Y/g,'').replace(/^\W|\W$|\W\W/,'');
(也就是说:删除YYYY,加上删除后留下的孤立分隔符)
(Which is to say: Remove YYYY, plus the orphaned separator left by its removal)
然后你可以在片刻格式调用中使用你的新格式字符串:
Then you can use your new format string in a moment format call:
someDate.format(formatYearlessL);
这必然会做出一些假设:
This necessarily makes some assumptions:
- 区域设置的月份+日数字格式的顺序与该区域设置的年份+月份+日期格式的顺序相匹配,并删除年份。
- 短格式仅在月和日之间使用分隔符(没有前导/尾随分隔符)。
- 短数字日期格式的分隔符始终为非字母数字。
- 格式由数字元素和分隔符组成,而不是带有文章的句子格式(请参阅RGPT下面关于西班牙语和葡萄牙语的评论,这些评论也适用于其他语言的长格式)。
- The order of the month + day numeric format for a locale matches the order for the year + month + day format for that locale, with the year removed.
- The short form uses separators only between month and day (no leading / trailing separators).
- The separator for a short numeric date format is always non-alphanumeric.
- The format consists of numeric elements and separators, rather than a sentence-form format with articles (see RGPT's comment below about Spanish and Portugese, which will also apply to long formats in some other languages).
快速查看 locale / * .js
,这些假设适用于每个语言环境文件我检查过,但可能有一些违反它们的区域设置。 (ETA:下面的评论指出德国短日期格式违反了第二个假设)
On a quick review of locale/*.js
, these assumptions hold true for every locale file I examined, but there may be some locales that violate them. (ETA: a comment below points out that a German short date format violates the second assumption)
作为一个额外的重要警告,这可能是脆弱的。未来版本的moment.js完全有可能改变当前数据的位置 longDateFormat
...
As an additional important caveat, this is likely to be fragile. It is entirely possible that a future version of moment.js will change the location of the data currently in longDateFormat
...
这篇关于使用Moment.js的区域设置和特定日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!