Home > OS >  How to get current week days javascript
How to get current week days javascript

Time:09-29

I want to get current weekdays

Let's say Today is 29 Wednesday (29 day and Wednesday Week)

How do I get this

*26 Sunday

*27 Monday

*28 Tuesday

*29 Wednesday

30 Thursday

31 Friday

1 Saturday

CodePudding user response:

The function you're looking for on a Date object is getDay(). It returns a number between 0 and 6 (where 0 is Sunday). You could create an array of day names and use the getDay function to fetch the name from it. E.g.

const dayNames = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursdsay',
    'Friday',
    'Saturday',
];

// get todays date
const today = new Date();
return dayNames(today.getDay()); 

You can read more about the getDay function on the MDN web docs here and the Date object here.

Similarly getDate() returns the date of the Date object.

CodePudding user response:

const name = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const now = Date.now();
const DAY = 60 * 60 * 24 * 1000;
const today = new Date(now).getDay();

for (let i = today; i >= 0; i--) {
  const date = new Date(now - DAY * i);
  console.log("*",name[date.getDay()], date.getDate());
}
for (let i = 1; i < 7 - today; i  ) {
  const date = new Date(now   DAY * i);
  console.log(name[date.getDay()], date.getDate());
}

  • Related