Expected Input:
const d1 = 01/11/2022
const d2 = 10/11/2022
Expected Output:
I want all dates between input dates but only Mon to Fri
01/11/2022
02/11/2022
03/11/2022
04/11/2022
07/11/2022
08/11/2022
09/11/2022
10/11/2022
CodePudding user response:
Hope This simple function would help you !
function parseDate(input) {
const parts = input.match(/(\d )/g);
return new Date(parts[2], parts[1]-1, parts[0])
}
function getDates(intialDate, finalDate) {
const date = parseDate(intialDate)
date.setTime(date.getTime() 24*3600000)
const finaldate = parseDate(finalDate);
if (finaldate.getTime() - date.getTime() > 24 * 360000000) return ['too many dates']
const array = []
while (finaldate.getTime() 24*36*200000 > date.getTime()) {
array.push(date.toJSON().slice(0, 10))
date.setTime(date.getTime() 24 * 3600000)
}
return array.map(elem => {
const parts = elem.split('-')
return [parts[2], parts[1], parts[0]].join('/')
})
}
const d1 = '01/11/2022'
const d2 = '10/11/2022'
console.log(getDates(d1,d2))
CodePudding user response:
Can you check this solution (using moment)
import moment from "moment";
const isWeekend = (date) => [0, 6].includes(new Date(date).getDay());
const enumerateDaysBetweenDatesWithoutWeekend = function (startDate, endDate) {
const dates = []
const currDate = moment(startDate).startOf("day");
const lastDate = moment(endDate).startOf("day");
const firstDate = currDate.clone().format("YYYY/MM/DD")
if (!isWeekend(firstDate)) dates.push(moment(firstDate).format("DD/MM/YYYY"));
while (currDate.add(1, "days").diff(lastDate) < 0) {
const date = currDate.clone().format("YYYY/MM/DD");
if (!isWeekend(date)) dates.push(moment(date).format("DD/MM/YYYY"));
}
return dates;
};
const a = moment("01/11/2022", "DD/MM/YYYY");
const b = moment("10/11/2022", "DD/MM/YYYY");
console.log(...enumerateDaysBetweenDatesWithoutWeekend(a, b));