Skip to content

Instantly share code, notes, and snippets.

@Meldiron
Last active August 1, 2021 11:01
Show Gist options
  • Save Meldiron/e2c999400e8c0d0520a702b55169f8e1 to your computer and use it in GitHub Desktop.
Save Meldiron/e2c999400e8c0d0520a702b55169f8e1 to your computer and use it in GitHub Desktop.
Typescript: Get current weekdays
// v1.0.1
// consts
const weekInMs = 1000 * 60 * 60 * 24 * 7;
const dayInMs = 1000 * 60 * 60 * 24;
// main function
const getWeekArray = (currentDate: Date, page: number) => {
if (page > 0) {
currentDate = new Date(currentDate.getTime() + weekInMs * page); // Add X weeks where X is page
} else if (page < 0) {
currentDate = new Date(currentDate.getTime() - weekInMs * (page * -1)); // Subtract X weeks where X is page
} else {
// page = 1 is already fine
}
// currentDate now includes pagination. We have any day inside correct week
// Get closest monday in the past
const mondayDate = new Date(currentDate.getTime());
if (currentDate.getDay() == 0) {
mondayDate.setDate(currentDate.getDate() - 7);
} else {
mondayDate.setDate(currentDate.getDate() - (currentDate.getDay() - 1));
}
// Prepare result, 7 days of the week
const mondayDateInMs = mondayDate.getTime();
const daysOfWeek = Array.from(Array(7).keys()).map((dayIndex) => {
return new Date(mondayDateInMs + dayInMs * dayIndex);
});
return daysOfWeek;
};
// Main code
// Page 0 means first page
const dateNow = new Date();
for (const page of [-3, -2, -1, 0, 1, 2, 3]) {
console.log(`Page ${page}:`, getWeekArray(dateNow, page));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment