[英]How to get the date ranges of a given week number in JS
I need to know the exact months that a week falls in if that week happens to be in 2 consecutive months. 如果该周恰好是连续两个月,那么我需要知道一周的确切月份。 For example 52nd week of 2016 falls in Dec 2016 and January 2017.Also 5th week of 2017 starts on 30th January - 5th February 2017.
例如,2016年的第52周分别在2016年12月和2017年1月.2017年的第5周也从2017年1月30日至2月5日开始。
So given a week number in a year, can I get the months it falls in. I need to know if there is any JS library that can easily achieve this. 因此,给定一年中的星期数,我能得到它的几个月吗?我需要知道是否有任何JS库可以轻松实现这一目标。
I know I can get a week number from a specific date value but have not seen a way to get a range of dates that date falls in so that I can derive the months from there .If momentJS or any other lib can do this, how can I use them to achieve this? 我知道我可以从特定的日期值中获得星期数,但还没有找到获取日期所属日期范围的方法,以便可以从中得出月份 。如果momentJS或任何其他lib可以做到这一点,我可以用它们来实现吗?
Thanks in advance 提前致谢
We want to create a date object for the beginning of a given week and the end. 我们要为给定的一周的开始和结束创建一个日期对象。
momentjs is a good library to make using date objects much easier. momentjs是一个很好的库,可以简化日期对象的使用。
var moment = require('moment');
function getMonths(weekNumber) {
var beginningOfWeek = moment().week(weekNumber).startOf('week');
var endOfWeek = moment().week(weekNumber).startOf('week').add(6, 'days');
console.log(beginningOfWeek.format('MMMM'));
console.log(endOfWeek.format('MMMM'));
}
Given a week number, we are creating a moment object and another one six days later. 给定一个星期数,我们将创建一个矩对象,然后再创建一个六天。 Then we log the month at the beginning and end of the week.
然后,我们在月份的开始和结束时记录月份。
Here's an example: 这是一个例子:
getMonths(5);
January
一月
February
二月
You can get week ending date easily by adding more 6 days 您可以通过增加6天来轻松获得星期结束日期
function getDateOfISOWeek(w, y) { var simple = new Date(y, 0, 1 + (w - 1) * 7); var dow = simple.getDay(); var ISOweekStart = simple; if (dow <= 4) ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1); else ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay()); return ISOweekStart; } function getDateRangeOfWeek(w, y) { var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var date = getDateOfISOWeek(w, y); var monthStart = monthNames[date.getMonth()]; // easily get ending date by adding 6 days more date.setDate(date.getDate() + 6); // then you can have months var monthEnd = monthNames[date.getMonth()]; return (monthStart == monthEnd) ? monthStart : [monthStart, monthEnd]; } console.log(getDateRangeOfWeek(52, 2016)); console.log(getDateRangeOfWeek(51, 2016)); console.log(getDateRangeOfWeek(5, 2017));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.