javascriptjquerydatenamesdays

Get last 7 days by names javascript


How to get the last seven days, from today, (by names) in java script. like if today is Wednesday, I want to get it like (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday).


Solution

  • Just add the days in the string array and iterate them backward by getting current date with new Date() this will return the index of current day

    const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    
    const d = new Date();
    let day = weekday[d.getDay()];
    
    var wanteddays = 8;
    var temp = d.getDay()
    while(wanteddays!=0){
        if (temp <0)
        temp = 6;
        console.log(weekday[temp]);
        temp = temp-1;
        wanteddays = wanteddays -1;
    }