Get the start date of this week to the end date of this week

1. Cause of the accident

        The schedule management in the recent project shows that you want to get the first day to the last day of the week. Click on the schedule in the table, as shown below

        

 

2. Writing method

        The framework uses vue. These are encapsulated functions  written in  methods  . Remember to define a  weekDates in the data above .

Encapsulation time function

        bz(time) {
            let date
            if (time) {
                date = new Date(time);
            } else {
                date = new Date(); // 可以传入任意一个日期
            }
            this.weekDates = this.getWeekDates(date); // 获取本周一到本周日的日期
            this.weekDates.forEach((item, index) => {
                this.weekDates[index] = this.format(item)
            })
        },
        format(time) {
            let nowTime = new Date(time)
            let year = nowTime.getFullYear()
            let month = (nowTime.getMonth() + 1) < 10 ? "0" + (nowTime.getMonth() + 1) : (nowTime.getMonth() + 1)
            let day = nowTime.getDate() < 10 ? "0" + nowTime.getDate() : nowTime.getDate()
            return year + "-" + month + "-" + day
        },
        getWeekDates(date) {
            const weekDates = [];
            const dayOfWeek = date.getDay(); // 获取给定日期的星期几,0表示星期日,1表示星期一,以此类推
            // 计算本周一的日期
            const monday = new Date(date);
            monday.setDate(date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1));
            weekDates.push(monday);
            // 计算本周二到本周六的日期
            for (let i = 1; i <= 5; i++) {
                const day = new Date(date);
                day.setDate(date.getDate() - dayOfWeek + i + (dayOfWeek === 0 ? 0 : 1));
                weekDates.push(day);
            }
            // 计算本周日的日期
            const sunday = new Date(date);
            sunday.setDate(date.getDate() - dayOfWeek + 7);
            weekDates.push(sunday);
            return weekDates;
        },

call method

        I wrote this paragraph in the watch monitor. When I click on the function that is triggered when I click on last week, week, next week, next week in the upper left corner, I will get the year, month and day from Monday to Sunday of last week ➡ this week. The year, month and day from Monday to Sunday ➡ The year, month and day from Monday to Sunday next week ➡ The year, month and day from Monday to Sunday next week

        whichWeek(val) {
            if (val == -1) {
                this.bz(new Date().getTime() - 60 * 1000 * 60 * 24 * 7)
            } else if (val == 0) {
                this.bz()
            } else if (val == 1) {
                this.bz(new Date().getTime() + 60 * 1000 * 60 * 24 * 7)
            } else if (val == 2) {
                this.bz(new Date().getTime() + 60 * 1000 * 60 * 24 * 14)
            }
        },

Guess you like

Origin blog.csdn.net/notagoodwriter/article/details/130715436