Reputation: 1999
I'm trying to get the date of Monday of the upcoming week, so for example, if I run the script now I will get 2021-09-13.
I tried solving this myself, and wrote this:
export function getMondayDate() {
const d = new Date();
const DAYS_IN_WEEK = 7;
var today = d.getDay()
const daysToMonday = (DAYS_IN_WEEK - today) + 1;
const Monday = d.getDate() + d.getDay() + daysToMonday;
return new Date(d.setDate(Monday));
}
I thought about getting the current day, so for example getDay()
will return 3
.
So, when subtracting DAYS_IN_WEEK
from today
, will result in the number 4
that would get Sunday and than to add 1
to get Monday.
So, from Today, it will be 5
days to get to Monday.
But for some reason I get the wrong date, I can't really see what's wrong here.
Upvotes: 0
Views: 91
Reputation: 17898
You can use Date.prototype.getDay to get the day in the week. From there, you have enough information to get when's the next monday.
E.g.
const nowMs = Date.now();
const today = new Date(nowMs);
/*
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday
*/
const dayOfTheWeek = today.getDay();
// Monday is 1st day of the week, so..
const itsSunday = dayOfTheWeek === 0;
let deltaDayToMonday;
if (itsSunday) {
deltaDayToMonday = 1; // monday is tomorrow
}
else {
deltaDayToMonday = 8 - dayOfTheWeek;
}
console.log(`Monday is in ${deltaDayToMonday} day(s)`);
/*
We're using the milliseconds to generate the new date for monday
To handle the dates overflowing months or years
*/
const nextMondayInMs = nowMs + (deltaDayToMonday * 24 * 60 * 60 * 1000);
const nextMondayUtc = new Date(nextMondayInMs);
console.log("Next monday is", nextMondayUtc.toLocaleString());
Upvotes: 0
Reputation: 351298
You shouldn't add d.getDay()
to d.getDate()
. You have already used d.getDate()
to determine daysToMonday
, so you should not use it again.
Secondly, if you want on a Sunday to get the next day as return value (instead of one week later), then you should add a % 7
in the formula.
Currently your function will return a date with a time part that is equal to the current time. Maybe you want to reset the time part to 0.
function getMondayDate() {
const d = new Date();
const daysToMonday = (7 - d.getDay()) % 7 + 1;
const monday = d.getDate() + daysToMonday;
return new Date(d.getFullYear(), d.getMonth(), monday);
}
console.log(getMondayDate().toString());
Upvotes: 2