How to can I make this sequence of date with tri-monthly. for eg. the input is `"2022-03-14" the input is dynamic it depends on the user input… I’m trying add + 10 days but isn’t working
The output I want
[
"2022-03-24",
"2022-04-04",
"2022-04-14",
"2022-04-24",
"2022-05-04",
"2022-05-14",
"2022-05-24",
"2022-06-04",
"2022-06-14",
"2022-06-24",
]
My code output which is worng
[
"2022-03-24",
"2022-04-14",
"2022-04-24",
"2022-05-14",
"2022-05-24",
"2022-06-14",
"2022-06-24",
"2022-07-14",
"2022-07-24",
]
function createSchedule(date, count){
date = new Date(date);
let day = date.getDate();// Get day in given date
let k = 0;
let days = k? [day - 10, day , day + 10] : [day, day + 10, day- 10];
let result = [];
if(day > 10){
k = +0
}else{
if(day > 20 ){
k = +1
}else{
k= +2
}
}
for(let i = 0; i < count; i++){
k= 1-k;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result
}
var dateRelease = new Date("03-14-2022");
var result = createSchedule(dateRelease, 9);
console.log(result)
>Solution :
A few issues in your attempt:
- After
let k = 0, the conditional operator onk?will always evaluate the second expression after:, which is[day, day + 10, day- 10]. - That array
[day, day + 10, day- 10]is not sorted, but should be. - The constants +0 and +1 and +2 are OK, but it looks odd that you use the unary plus here. It could just be 0, 1 and 2.
- The assignment
k = 1 - kassumes you only have two entries in yourdaysarray, but you have three, so use modular arithmetic:k = (k + 1) % 3
Here is a correction:
function createSchedule(date, count) {
date = new Date(date);
let day = date.getDate();
let firstDay = 1 + (day - 1) % 10;
let days = [firstDay, firstDay + 10, firstDay + 20];
let k = days.indexOf(day);
let result = [];
for (let i = 0; i < count; i++) {
k = (k + 1) % 3;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result;
}
var dateRelease = new Date("2022-03-14");
var result = createSchedule(dateRelease, 25);
console.log(result);