B
B
Binarix2016-02-22 15:52:35
JavaScript
Binarix, 2016-02-22 15:52:35

How to get the date of the next Monday in JS?

I need to display the date of next Monday in JS.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Murzin, 2016-02-22
@Binarix

From today

date = new Date();
m = new Date();
if(date.getDay()){m.setDate(date.getDate() + 8 - date.getDay())} else {m.setDate(date.getDate() + 1)}
alert(m);

A
Alexey, 2019-09-27
@Joomler

The above method is not quite universal.
Although absolutely true in the context of the question posed.
As far as I understand, it is suitable for Monday, but not for any desired day of the week.
In addition, it will indicate the date of the next Monday, but not the nearest one. And there is a difference. And for some cases it is extremely important.
Therefore, I offer an alternative solution. Perhaps it will be useful:

var date = new Date(),
    targetDay = 5, // пятница, начиная с вс=0
    targetDate = new Date(),
    delta = targetDay - date.getDay();
if (delta >= 0) {targetDate.setDate(date.getDate() + delta)}
else {targetDate.setDate(date.getDate() + 7 + delta)}
alert(targetDate);

Perhaps, after the calculation, you will need to display this desired date in Russian words. Here is one option:
var targetNumber = targetDate.getDate();
var targetMonth = targetDate.getMonth();
switch(targetMonth) {
    case 0: targetMonth = 'января'; break;
    case 1: targetMonth = 'февраля'; break;
    case 2: targetMonth = 'марта'; break;
    case 3: targetMonth = 'апреля'; break;
    case 4: targetMonth = 'мая'; break;
    case 5: targetMonth = 'июня'; break;
    case 6: targetMonth = 'июля'; break;
    case 7: targetMonth = 'августа'; break;
    case 8: targetMonth = 'сентября'; break;
    case 9: targetMonth = 'октября'; break;
    case 10: targetMonth = 'ноября'; break;
    case 11: targetMonth = 'декабря'; break;
}
var targetYear = targetDate.getFullYear();
alert(targetNumber + ' ' + targetMonth + ' ' + targetYear + ' года');

In practice it is checked up and works ( example ).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question