I want to find date of previous Wednesday in ‘YYYY-MM-DD" format given date string = ‘YYYY-MM-DD". Exclusive of today being Wednesday.
I also want to find date of next Wednesday in ‘YYYY-MM-DD" format given date string = ‘YYYY-MM-DD". Exclusive of today being Wednesday.
date_Event = '2022-10-05';
function prevWed() {
const str_1 = date_Event;
const [year, month, day] = str_1.split('-');
const date_1 = new Date(+year, month - 1, +(day - 7));
alert(date_1.toISOString().split('T')[0]); // 2022-09-21 FINE!
}
function nextWed() {
const str_2 = date_Event;
const [year, month, day] = str_2.split('-');
// this is OK, as long as today = "3" but I need the next Wed. regardless of today
const date_2 = new Date(+year, month - 1, +(day + 7));
alert(date_2.toISOString().split('T')[0]); // 2023-06-14 COMPLETELY WRONG!
}
prevWed();
nextWed();
>Solution :
The problem is +(day + 7). The day is a string, let’s say its "05", while ("05" + 7) resolves into "057" and +"057" is 57; You need to convert the day into number first and then do the addition without the parenthesis: +day + 7
date_Event = '2022-10-05';
function prevWed() {
const str_1 = date_Event;
const [year, month, day] = str_1.split('-');
const date_1 = new Date(+year, month - 1, +day - 7);
alert(date_1.toISOString().split('T')[0]); // 2022-09-21 FINE!
}
function nextWed() {
const str_2 = date_Event;
const [year, month, day] = str_2.split('-');
// this is OK, as long as today = "3" but I need the next Wed. regardless of today
const date_2 = new Date(+year, month - 1, +day + 7);
alert(date_2.toISOString().split('T')[0]); // 2023-06-14 COMPLETELY WRONG!
}
prevWed();
nextWed();