问题描述
有没有更好的方法从包含位置适当分隔符的日期中仅获取日和月?
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="http://www.51sjk.com/Upload/Articles/1/0/340/340175_20221220100323917.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>