問題描述
我在我的項目中使用 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);
這必然做出一些假設:
- 區域設置的月 + 日數字格式的順序與該區域設置的年 + 月 + 日格式的順序匹配,但刪除了年份.
- 短格式僅在月和日之間使用分隔符(沒有前導/尾隨分隔符).
- 短數字日期格式的分隔符始終為非字母數字.
- 格式由數字元素和分隔符組成,而不是帶有文章的句子格式(請參閱下面 RGPT 關于西班牙語和葡萄牙語的評論,這也適用于其他一些語言的長格式).
快速回顧一下 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模板網!