问题描述
我正在尝试获取某个日期的周数,但我希望它能够在一周的第一天使用可变的值.用户可以设置一周的第一天.我找不到 javascript 解决方案,所以我尝试了 moment.不幸的是,我找不到设置一周第一天的方法.例如.星期天是美国,星期一是欧盟,但如果它也可以是其他任何一天就好了.
I'm trying to get the weeknumer of a date, but I want it to work with a variable first day of the week. A user is able to set the first day of the week. I couldn't find a javascript solution, so I tried moment. Unfortunately, I couldn't find a way to set the first day of the week. E.g. Sunday for US, Monday for the EU, but it would be nice if it could be any other day as well.
推荐答案
Moment 支持 i18n,您可以全局更改区域设置或在本地更改区域设置 并根据区域设置规则更新一周的第一天.然后你可以使用 week()
那:
Moment supports i18n, you can change locale globally or change locales locally and update first day of the week according locale rules. Then you can use week()
that:
获取或设置一年中的第几周.
因为不同的语言环境定义了不同的年份编号,Moment.js 添加了 moment#week
来获取/设置本地化的年份周.
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
)如何使用不同的语言环境具有不同的周值:
Here a example showing how the same day (e.g. 2017-08-13
) has different week value using different locales:
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 locale,你可以简单地使用updateLocale
方法自定义一周的第一天(对于当前的locale),只需改变dow的值
(星期几)键(以及 week
对象的 doy
键,如果需要).请参阅文档的自定义部分以获取有关区域设置自定义的更多信息.
If you don't want to change moment locale, you can simply customize the first day of the week (for the current locale) using updateLocale
method, just change the value of dow
(day of week) key (and doy
key too, if needed) of the week
object. See Customize section of the docs to get more info about locale customization.
这是一个活生生的例子:
Here a live example:
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>
这篇关于MomentJS 使用可变的一周第一天获取周数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!