Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

arrays - Javascript - How do i get every date in a week from a given week number and year

How do I get every weekday (monday through friday) in a week from a given week number

input

var weekNumber = "week + " " + year"; //"35 2020"

Wanted output

var weekArray = ["2020-08-24", "2020-08-25", "2020-08-26", "2020-08-27", "2020-08-28"];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example building on top of: javascript calculate date from week number

Get the first date of the week, then return an array of 7 elements, incrementing the date for each element.

If the day number goes above the number of days in the month, then add one to the month temp.m and reset the day temp.d equal to one.

function getISOWeek(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());
    const temp = {
      d: ISOweekStart.getDate(),
      m: ISOweekStart.getMonth(),
      y: ISOweekStart.getFullYear(),
    }
    //console.log(ISOweekStart)
    const numDaysInMonth = new Date(temp.y, temp.m + 1, 0).getDate()
    
    return Array.from({length: 7}, _ => {
      if (temp.d > numDaysInMonth){
        temp.m +=1;
        temp.d = 1;
        // not needed, Date(2020, 12, 1) == Date(2021, 0, 1)
        /*if (temp.m >= 12){
          temp.m = 0
          temp.y +=1
        }*/
      }      
      return new Date(temp.y, temp.m, temp.d++).toUTCString()
    });
}

// var weekNumber = "week + " " + year"; //"35 2020"
const weekNumber = "53 2020";

const weekYearArr = weekNumber.split(" ").map(n => parseInt(n))

const weekOut = getISOWeek(...weekYearArr) 

console.log(weekOut);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...