How to get the date ranges of a given week number

2019-07-31 17:20发布

问题:

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.

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.

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?

Thanks in advance

回答1:

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.

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



回答2:

You can get week ending date easily by adding more 6 days

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));