我正在尝试获取日期的周数,但我希望它能与一周的可变第一天一起使用。用户可以设置一周的第一天。我找不到 javascript 解决方案,所以我试了一下。不幸的是,我找不到设置一周第一天的方法。例如。美国是星期天,欧盟是星期一,但如果也可以是其他任何一天就好了。
最佳答案
时刻支持i18n , 你可以 change locale globally或 change locales locally并根据语言环境规则更新一周的第一天。然后你可以使用week()
那:
Gets or sets the week of the year.
Because different locales define week of year numbering differently, Moment.js added
moment#week
to get/set the localized week of the year.The week of the year varies depending on which day is the first day of the week (Sunday, Monday, etc), and which week is the first week of the year.
这里有一个示例显示同一天(例如 2017-08-13
)如何使用不同的语言环境具有不同的星期值:
moment.locale('en');
var now2 = moment('2017-08-13');
console.log( now2.week() ); // 33
moment.locale('it');
var now1 = moment('2017-08-13');
console.log( now1.week() ); // 32
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
如果您不想更改 moment 区域设置,您可以使用 updateLocale
方法简单地自定义一周的第一天(对于当前区域设置),只需更改 dow 的值
(星期几)键(和 week
对象的 doy
键,如果需要的话)。参见 Customize文档部分以获取有关区域设置自定义的更多信息。
这是一个活生生的例子:
var now1 = moment('2017-08-13');
console.log( now1.week() ); // 33
moment.updateLocale('en', {
week: {
dow : 1, // Monday is the first day of the week.
}
});
var now2 = moment('2017-08-13');
console.log( now2.week() ); // 32
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
关于javascript - MomentJS 获取具有可变一周第一天的周数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45774927/