This is a collection of helpful javascript date functions.
- Get the current week first date.
const getCurrentWeekFirstDt = (currentDt = new Date()) => {
const weekFirstDt = new Date(currentDt);
const offset = currentDt.getDate() - currentDt.getDay();
weekFirstDt.setDate(offset);
return weekFirstDt;
}
- Get the current week last date.
const getCurrentWeekLastDt = (currentDt = new Date()) => {
const weekLastDt = getCurrentWeekFirstDt(currentDt);
const offset = weekLastDt.getDate() + 6;
weekLastDt.setDate(offset);
return weekLastDt;
}
- Subtract days.
const subDays = (daysCount, currentDate = new Date()) => {
if (!daysCount) return currentDate;
currentDate.setDate(currentDate.getDate() - Number(daysCount));
return currentDate;
}
- Add days.
const addDays = (daysCount, currentDate = new Date()) => {
if (!daysCount) return currentDate;
currentDate.setDate(currentDate.getDate() + Number(daysCount));
return currentDate;
}
- Get yesterday's date.
const yesterday = (currentDate) => subDays(1, currentDate)
- Get tomorrow's date.
const tomorrow = (currentDate) => addDays(1, currentDate)
- Get an array of dates between two dates.
const getDateArray = (startDate, endDate) => {
// An additional check here would be to reverse the dates
// if startDate is greater than endDate
let currentDate = startDate;
const dates = [];
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = tomorrow(currentDate);
}
return dates;
}
- Get all dates within the current week.
const getWeekDates = (currentDate = new Date()) => {
return getDateArray(
getCurrentWeekFirstDt(currentDate),
getCurrentWeekLastDt(currentDate)
);
}
- Get the current month first date.
const getMonthFirstDt = (currentDate = new Date()) => new Date(
currentDate.getFullYear(), currentDate.getMonth(), 1
);
- Get the current month last date.
const getMonthLastDt = (currentDate = new Date()) => new Date(
currentDate.getFullYear(), currentDate.getMonth() + 1, 0
)