問題描述
有沒有更好的方法從包含位置適當分隔符的日期中僅獲取日和月?
Is there any better way for getting only day and month from a date including location appropriate separator?
我有一個先獲取分隔符的解決方案:
I have a solution that gets separator first:
function getDateSep() {
var temp = moment().format('L');
var locale = moment().locale;
var datesep = temp.substring(5, 6);
return datesep;
}
然后像這樣構建日期:
var sep = function getDateSep()
var date = date.format('D' + sep + 'M'+ sep)
是否有動態構建整個日期的解決方案?
Is there a solution that builds the whole date dynamically?
我想要達到的結果是:31.01 (dd.mm)31/01 (日/毫米)01.31 (mm.dd)01/31 (mm/dd) 等
The result I want to achieve would be like: 31.01 (dd.mm) 31/01 (dd/mm) 01.31 (mm.dd) 01/31 (mm/dd) etc
推薦答案
如鏈接問題中所述:實現所需的一種方法是獲取本地化 longDateFormat,然后使用正則表達式刪除年份部分.
Daniel T. 在評論中強調該解決方案不適用于 en-CA
等語言環境,因此我將提供考慮到 一些 的更新解決方案> 以年份部分開頭的其他語言環境.
Daniel T. highlighted in comments that the solution will not work in locales like en-CA
, so I'm going to provide an updated solution that takes in account some other locales that starts with year part.
如果您需要支持 every 語言環境,您可以使用 ad hoc 條件來定位它們,就像我在以下代碼段中為 ar-ly
所做的那樣.
Probably there are some other locales the are not convered with /.YYYY/
and /YYYY./
RegExp, if you need to support every locale you can target them with ad hoc condition, as I made for ar-ly
in the following snippet.
這里的代碼示例顯示了不同語言環境中可能的輸出:
Here a code sample the shows possible output in various locales:
function changeLang(value){
moment.locale(value);
// Get locale data
var localeData = moment.localeData();
var format = localeData.longDateFormat('L');
// Manage custom cases
if( value === "ar-ly"){
format = 'D/u200FM';
}
// if( value === ...) possible othter cases
// Check locale format and strip year
if( format.match(/.YYYY/g) ){
format = format.replace(/.YYYY/, '');
}
if( format.match(/YYYY./g) ){
format = format.replace(/YYYY./, '');
}
var res = moment().format(format);
$("#result").html(res);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
<select onchange="changeLang(value)">
<option value="en">EN</option>
<option value="en-CA">en-CA (Canada)</option>
<option value="eo">eo (Esperanto)</option>
<option value="de">DE</option>
<option value="it">IT</option>
<option value="hu">hu (Hungarian)</option>
<option value="ja">ja (Japanese)</option>
<option value="lv">lv (Latvian)</option>
<option value="fr">FR</option>
<option value="zh-hk">zh-hk - Chinese (Hong Kong)</option>
<option value="ar-ly">ar-ly - Arabic (Lybia)</option>
</select>
<div id="result"></div>
這篇關于顯示日期和月份,根據區域設置不顯示年份的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!