时刻js中的自定义长日期格式
有没有办法根据语言环境为长日期的时刻添加自定义格式代码?
Is there a way to add a custom format code to moment for long dates based on locale?
例如:
moment().format("L")
是一种现有格式,将打印语言环境的长日期(包括年份),但如果我想添加自己的排除年份,如下所示:
is an existing format that will print the long date for the locale (including the year), but if I wanted to add my own that excluded the year like this:
moment().format("LTY")
刚刚在给定语言环境中打印月份和日期.
moment().format("LTY")
that just printed the month and day in a given locale.
我该怎么做?
推荐答案
阅读 长日期格式.您可以使用以下方法替换默认的长日期格式对象:
Read the section on long date formats. You'd replace the default long date format object using:
moment.updateLocale('en', {
longDateFormat : {
LT: "h:mm A",
LTS: "h:mm:ss A",
L: "MM/DD", // Remove year
LL: "MMMM Do YYYY",
LLL: "MMMM Do YYYY LT",
LLLL: "dddd, MMMM Do YYYY LT"
}
});
然后使用:
var x = moment().format('L');
Moment 解析传递给 format 的字符串以查找标记.如果您想添加自定义标记,如LTY",您还需要将其添加到本地格式化标记列表中:
Moment parses the string passed to format looking for tokens. If you want to add a custom token like "LTY" you'll also need to add it to the list of local formatting tokens:
var localFormattingTokens = /([[^[]*])|(\)?(LTS|LT|LL?L?L?|l{1,4})/g;
将更改为(添加 LTY):
would change to (LTY added):
var localFormattingTokens = /([[^[]*])|(\)?(LTY|LTS|LT|LL?L?L?|l{1,4})/g;
并使用新令牌更新默认长日期格式:
and update the default long date formats with the new token:
var defaultLongDateFormat = {
LTY : 'MM/DD HH:mm', // format for new token
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'dddd, MMMM D, YYYY h:mm A'
};
那么,如果你想要其他格式:
then, if you wanted some other format:
moment.updateLocale('en', {
longDateFormat : {
LTY: 'MM/DD HH:mm', // new format for token here
LT: "h:mm A",
LTS: "h:mm:ss A",
L: "MM/DD/YYYY",
LL: "MMMM Do YYYY",
LLL: "MMMM Do YYYY LT",
LLLL: "dddd, MMMM Do YYYY LT"
}
});
最后:
var x = moment().format('LTY');
但是您必须检查这将对其他代码产生什么影响.此外,每次更新 moment.js 源时,您都必须应用相同的更改,无法使用 CDN,并且您的代码无法使用标准 moment.js 库移植到其他站点.
but you'd have to check what that is going to do to other code. Also, you'd have to apply the same changes every time you update the moment.js source, couldn't use a CDN and your code would not be portable to other sites using the standard moment.js library.
所以坚持updateLocale 做事的方式.或者干脆做:
So stick to the updateLocale way of doing things. Or just do:
var LTY = 'MM/DD HH:mm';
var d = new moment().format(LTY);
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.js"></script>
你就完成了.
请注意,此处使用语言环境"是用词不当.格式化偏好与用户所在的位置(即他们的语言环境)无关,而en"是一种在大量语言环境中使用的语言,对于如何格式化日期有非常不同的偏好.
Note that the use of "locale" here is a misnomer. Formatting preferences have nothing to do with where the user is located (i.e. their locale), and "en" is a language that is spoken in a huge number of locales which have very different preferences for how to format a date.
相关文章