skip to Main Content

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

3

Answers


  1. 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;
    }
    Login or Signup to reply.
  2. function getDayName(date, len, local) {
      let newDate = new Date(date);
      let weekDays = [];
    
      Array(len).fill(1).forEach((subDay) => {
        newDate.setDate(newDate.getDate() - subDay);
        weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
      })
      return weekDays;
    }
    

    to use:

    getDayName(Date.now(), 7, 'en-EN') 
    OR
    getDayName('10/12/2022', 7, 'en-EN')
    

    Typescript:

    function getDayName(date: Date | string | number, len: number, local:string) {
      let newDate = new Date(date);
      let weekDays: string[] = [];
    
      Array(len).fill(1).forEach((subDay: number) => {
        newDate.setDate(newDate.getDate() - subDay);
        weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
      })
      return weekDays;
    }
    
    Login or Signup to reply.
  3. This should order an array to follow your wished output.

        var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        var currentDay = days[ (new Date()).getDay()]
        days =  days.reverse();
        var x = days.indexOf(currentDay)
        var daysLastSeven =  days.slice(x).concat(days.slice(0,x))
    
        console.log(daysLastSeven)
     
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search