我在我的项目中使用 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 well but sometimes I need show a date without a 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 like L,LL,LLL
but without the 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$|WW/,'');
(也就是说:删除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);
这必然做出一些假设:
快速回顾一下 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 的语言环境和特定日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!