时刻获取在语言环境格式化的日期 [英] moment get date formatted on locale

查看:81
本文介绍了时刻获取在语言环境格式化的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从文档设置格式 l 开始,格式为M / D / YYYY。
有没有办法以 D / M M / D 格式获取日期,具体取决于语言环境?这是我现在的代码。

From the moment docs setting format as l returns in format "M/D/YYYY". Is there a way to get the date in just D/M or M/D format depending on locale? Here is the code i have right now.

var locale = window.navigator.userLanguage || window.navigator.language;
moment.locale(locale);
var momentTime = moment(d);
console.log(momentTime.format('l'));

例如,如果语言环境是法语那么日期应以 D / M 格式返回,如果区域设置为 english-us ,则应返回日期在 M / D 格式自动。

For instance if the locale is French then the date should be returned in D/M format and if the locale is english-us then the date should be returned in M/D format automatically.

推荐答案

一种方法可以做什么你需要获得本地化的 longDateFormat ,然后用正则表达式删除年份部分。

One way to do what you need is getting localized longDateFormat and then remove the year part with a regular expression.

这里有一个工作示例使用 localeData 和然后 longDateFormat 。我不确定它是否适用于每个语言环境,但它为 fr en-us (可能还有很多其他人)。

Here a working example that uses localeData and then longDateFormat. I'm not sure that it will work for each locale, but it gives the right result for fr and en-us (and probably many others).

var locale = window.navigator.userLanguage || window.navigator.language;
moment.locale(locale);

// Get locale data
var localeData = moment.localeData();
var format = localeData.longDateFormat('L')
// Remove year part
format = format.replace(/.YYYY/, ''); 

var momentTime = moment();
console.log(momentTime.format(format));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

这篇关于时刻获取在语言环境格式化的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆