简体   繁体   English

使用javascript获取年份和日历周的开始和结束日期

[英]Get the weeks starting and ending date from year and calendar week with javascript

I need to get the weeks starting and ending date with Javascript/ moment.js 我需要使用Javascript / moment.js获取开始和结束日期的几周

As input i have two values: year and week, which is the isoweek of moment.js 作为输入,我有两个值:年和周,这是moment.js的等周

year = '2016' week = '1' 年='2016'周='1'

should give me the 04.01.2016 and 10.01.2016 应该给我04.01.2016和10.01.2016

where the date has the german format moment().format('DD.MM.YYYY'); 日期的德语格式为moment()。format('DD.MM.YYYY');

The solution from your comment will produce an incorrect result on 01.01.2017: 您评论中的解决方案将在01.01.2017上产生不正确的结果:

moment([2017,0,1]).year(2017).isoWeek(1).startOf('isoweek').format('DD.MM.YYYY');
// = '04.01.2016'

This one is more stable: 这个比较稳定:

//var year = 2016;
//var week = 1;
var startDate = moment([year, 5, 30]).isoWeek(week).startOf('isoweek'); 
var endDate = moment(startDate).endOf('isoweek');
startDate.format('DD.MM.YYYY'); // = '04.01.2016'
endDate.format('DD.MM.YYYY'); // = '10.01.2016'

Explanation: if you initialize the moment instance with a date from week 53 of the previous year in conjunction with isoWeek or week , the year component of that moment instance is set to the previous year. 说明:如果使用从上一年的第53周开始的日期与isoWeekweek一起初始化时刻实例,则该时刻实例的year组件将设置为上一年。 All additional moment methods then operate on the "wrong" year. 然后,所有其他矩方法都将在“错误的”年份运行。 Therefore use moment([year, 5, 30]) to initialize the moment instance. 因此,请使用moment([year, 5, 30])初始化一下矩实例。 Any other day after the Jan 3rd works for 2016 too of course, only the few days that belong to week 53 of the previous year cause that problem. 当然,2016年1月3日之后的任何其他日子,也只有属于上一年第53周的几天才引起该问题。

moment([2016]).isoWeek(1).startOf('isoWeek').format('DD.MM.YYYY')  // "02.01.2015"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM