JavaScript: How to Get the Week of a Day

Keywords: Javascript

What we will encounter is the need to get the start and end dates of the week today or one day.

Let's get the start and end date of the week today. We can get today's day by (new Date).getDay(), and then subtract or add a certain number of days, which is the start and end date of the week.

function getWeekStartAndEnd() {
    const oneDayTime = 1000 * 60 * 60 * 24; // The total number of milliseconds in a day
    const today = new Date();
    const todayDay = today.getDay(); // Get what day it is today, assuming it is Wednesday 3
    const startDate = new Date(
        today.getTime() - oneDayTime * (todayDay - 1)
    );
    const endDate = new Date(today.getTime() + oneDayTime * (7 - todayDay));

    return { startDate, endDate };
}
const week = getWeekStartAndEnd();
console.log(week.startDate, week.endDate);

Is it perfect? But here's a big bug! Note: If today is Sunday, then todayDay will be 0. If we follow the above idea, Monday will be the date of next Monday and Sunday will be the date of next Sunday. Therefore, we need special treatment here, when todayDay is 0, we assign it to 7. At the same time, we can also pass in a timestamp to get the week of a particular day.

Final solution

function getWeekStartAndEnd(timestamp) {
    const oneDayTime = 1000 * 60 * 60 * 24; // The total number of milliseconds in a day
    const today = timestamp ? new Date(timestamp) : new Date();
    const todayDay = today.getDay() || 7; // If that day is weekend, the mandatory assignment is 7
    const startDate = new Date(
        today.getTime() - oneDayTime * (todayDay - 1)
    );
    const endDate = new Date(today.getTime() + oneDayTime * (7 - todayDay));

    return { startDate, endDate };
}

extend

What if I want to export all the dates of today's week? It's easy to get the first day of the week, and then add the timestamp of one DayTime*i on the first day, which is the date of the first day, or add one DayTime on the basis of the previous day.

function getAllWeekToday() {
    const oneDayTime = 1000 * 60 * 60 * 24;
    const today = new Date();
    const todayDay = today.getDay() || 7; // If that day is weekend, the mandatory assignment is 7
    const startDate = new Date(
        today.getTime() - oneDayTime * (todayDay - 1)
    );
    let dateList = [startDate];

    for (let i = 1; i < 7; i++) {
        dateList.push(new Date(startDate.getTime() + oneDayTime * i));
    }
    return dateList;
}

More articles can be clicked: Mosquito blog

Posted by bobohob on Fri, 04 Oct 2019 04:56:15 -0700