Getting the date of next Monday
Asked Answered
W

12

55

How can I get the next Monday in JavaScript? I can't find anything of this in the internet and I have also tried a lot of codes and understanding of this but I can't really do it.

Here's my code:

var d = new Date();
var day = d.getDay();
d = new Date(d.setDate(d.getDate() + day + (day == 0 ? -6 : 2)));
Williwaw answered 12/10, 2015 at 10:4 Comment(3)
If today is Monday, then you want next Monday or today's date?Oeildeboeuf
Check also: #9481658Heckle
Does this answer your question? Get next date from weekday in JavaScriptDike
O
82

This will retrieve the next Monday, returning the current date if already a Monday:

var d = new Date();
d.setDate(d.getDate() + (1 + 7 - d.getDay()) % 7);
console.log(d);

To return the following Monday even if the current date is a Monday:

var d = new Date();
d.setDate(d.getDate() + (((1 + 7 - d.getDay()) % 7) || 7));
console.log(d);
Oeildeboeuf answered 12/10, 2015 at 10:17 Comment(5)
@MouradIdrissi It gives the correct result for me. var d = new Date("2017-09-26"), followed by the code above yields Monday 2 Oct, 2017, which is the next Monday after Tuesday 26 Sep, 2017.Haskell
@VictorZamanian is correct; if you pass 32 as the arg for setDate() into a month with 30 days, you will get the 2nd date of the following month.Metternich
Only the date becomes correct here. The time (hours, minutes, seonds) changes.Sedillo
I don't think this works – if today is Monday then this will set the date to today. d.getDay() will be 1, 1 + 7 -1 will be 7, 7 % 7 will be 0, so you'll get setDate(d.getDate() + 0) – so, not the next Monday, but the same day.Urian
@Urian which is exactly what it states it would do in the first case, and the reason why the second case has the || 7 attached at the end. If the first expression yields 0 as you pointed out, this will be interpreted as falsy, leading to the OR to evaluate and the whole expression to yield 7, which results in the next same weekday as today is.Countable
T
36

If the actual day of the week you want is variable (Sunday, Thursday, ...) and you want a choice whether today could be a possible match or not, and it might be that you want to start with another date (instead of today), then this function may be useful:

function getNextDayOfTheWeek(dayName, excludeToday = true, refDate = new Date()) {
    const dayOfWeek = ["sun","mon","tue","wed","thu","fri","sat"]
                      .indexOf(dayName.slice(0,3).toLowerCase());
    if (dayOfWeek < 0) return;
    refDate.setHours(0,0,0,0);
    refDate.setDate(refDate.getDate() + +!!excludeToday + 
                    (dayOfWeek + 7 - refDate.getDay() - +!!excludeToday) % 7);
    return refDate;
}

console.log("Next is: " + getNextDayOfTheWeek("Wednesday", false));
Taper answered 30/1, 2019 at 9:36 Comment(4)
This is exactly what i needed and wonder why this answer isn't getting more upvote ... is there a way to format the output to DD MM YYYY? @TaperLaticialaticiferous
@KolawoleEmmanuelIzzy, sure there is. There is toLocaleDateString which has many formatting options. Check out the many questions on the subject.Taper
@Taper Your solution is very flexible and practical. Personally I would change the boolean addition/subtraction, and that's mostly because TypeScript won't allow it. I would use unary plus to explicitly convert the boolean to 0 or 1.Frankish
Absolutely the best answerOft
F
21

This will give next Monday if today is Monday

var d = new Date();
d.setDate(d.getDate() + (7-d.getDay())%7+1);

This will result in today if today is Monday

var d = new Date();
d.setDate(d.getDate() + ((7-d.getDay())%7+1) % 7);
Fireboard answered 12/10, 2015 at 10:16 Comment(3)
this works fine in my console, but not in my nodejs codeManas
works identically for me - if you gave a little more information than it doesn't work that'd be just peachy - considering this code gives the same results as the code you accepted, I think you are probably doing it wrongFireboard
I dropped this code in JS fiddle. It worked fine. When I dropped it into my meteor app yesterday, I was getting a date for 14Manas
B
5

If you need to handle time zones, one option would be to use the UTCDate methods setUTCDate() and getUTCDate(). This allows for consistency so the calculation is the same no matter the time zone setting.

var d = new Date();
d.setUTCDate(d.getUTCDate() + (7 - d.getUTCDay()) % 7 + 1);

(This is the example from above where on a Monday the following Monday is returned)

Bosporus answered 8/5, 2017 at 0:47 Comment(0)
D
5

This is my solution

var days =[1,7,6,5,4,3,2];
var d = new Date();
d.setDate(d.getDate()+days[d.getDay()]);
console.log(d);
Dagda answered 27/7, 2020 at 15:30 Comment(0)
H
3
var closestMonday = () => {
    var curr_date = new Date(); // current date
    var day_info = 8.64e+7; // milliseconds per day
    var days_to_monday = 8 - curr_date.getDay(); // days left to closest Monday
    var monday_in_sec = curr_date.getTime() + days_to_monday * day_info; // aleary Monday in seconds from 1970 
    var next_monday = new Date(monday_in_sec); // Monday in date object
    next_monday.setHours(0,0,0);
    return next_monday;
}
Hodgepodge answered 27/2, 2018 at 10:11 Comment(0)
R
3

Other responses seems not to take into account that "next Monday" should be at the beginning of the day. Here's how I've implemented it recently:

function getNextMonday() {
  const now = new Date()
  const today = new Date(now)
  today.setMilliseconds(0)
  today.setSeconds(0)
  today.setMinutes(0)
  today.setHours(0)

  const nextMonday = new Date(today)

  do {
    nextMonday.setDate(nextMonday.getDate() + 1) // Adding 1 day
  } while (nextMonday.getDay() !== 1)

  return nextMonday
}
Reg answered 22/4, 2021 at 14:23 Comment(0)
E
1

Or more simple:

let now = new Date();
let day = 1; // Monday

if (day > 6 || day < 0) 
  day = 0;
    
while (now.getDay() != day) {
  now.setDate(now.getDate() + 1);
}
now.setDate(now.getDate() + 1);

console.log(now); // next Monday occurrence
Economy answered 9/9, 2020 at 23:10 Comment(0)
T
1

Another way is to find the offset (in number of days) to the day you want, turn that into milliseconds, and add it to you starting date:

let d = new Date();
const day = d.getDay();
const targetDay = 1;  // Monday
let dayOffset = targetDay - day;
if (dayOffset < 0) dayOffset += 7;

d = new Date(d.getTime() + (dayOffset * 24 * 3600 * 1000));
Tightfisted answered 26/5, 2021 at 15:58 Comment(0)
S
0

Please try this

d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1);
alert(new Date(d.setDate(diff)));
Syneresis answered 12/10, 2015 at 10:6 Comment(0)
R
0

Using moment.js,

moment().add(7, 'days').calendar();
Residue answered 12/10, 2015 at 10:13 Comment(3)
The question was not > Which library / Framework can i use ? <Deutschland
Is it mentioned anywhere in the original question? The person was looking for a solution and I gave mine using a popular library.Residue
But also, this simply adds 7 days to the current day, it doesn't get you the next Monday on any arbitrary day that the code is run on..Pussyfoot
E
0

I see many answers and trust me, I've done some digging.

In the case you want to get next Monday - 00:00:00 - regardless of time zone try the following snippet. It works with input ranging from 00:00:00 to 23:59:59.

function getNextMonday(d) {
    let date = new Date(new Date(d.setUTCDate(d.getUTCDate() + (7 - d.getUTCDay()) % 7 + 1)).setUTCHours(0,0,0));
    let nextMonday = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0)).toISOString();
    
    return nextMonday;
}

console.log(getNextMonday(new Date("2023-12-03T00:00:00.000+0000")));
console.log(getNextMonday(new Date("2023-12-03T23:59:59.000+0000")));
console.log(getNextMonday(new Date()));

Hope I could be of service :)

Ewan answered 5/12, 2023 at 0:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.