js,vue, 获取指定日期的那一周的开始、结束日期(从周日~周六)

需求:  给定一个日期,如: 2019-11-01, 获取该日期所在的这一周的开始时间、结束时间(按周日~周六算)

当执行: this.getWeekStartAndEnd('')的时候, 默认回去的问今天所在一周的开始、结束日期,

     执行:this.getWeekStartAndEnd('2019-11-01'),  会输出  10.27~11.02

// 日期格式化
        formatDate(date) {
            var myyear = date.getFullYear();
            var mymonth = date.getMonth() + 1;
            var myweekday = date.getDate();
            if (mymonth < 10) {
                mymonth = "0" + mymonth;
            }
            if (myweekday < 10) {
                myweekday = "0" + myweekday;
            }
            return mymonth + "." + myweekday
        },
        // 获取指定日期的那一周的开始、结束日期
        getWeekStartAndEnd(val) {
            let now = '';
            if(val) {
                now = new Date(val); // 日期
            } else {
                now = new Date(); // 日期
            }
            let nowDayOfWeek = now.getDay(); // 本周的第几天
            let nowDay = now.getDate(); // 当前日
            let nowMonth = now.getMonth(); // 当前月
            let nowYear = now.getYear(); // 当前年

            let weekStart = this.getWeekStartDate(nowYear, nowMonth, nowDay, nowDayOfWeek)
            let weekEnd = this.getWeekEndDate(nowYear, nowMonth, nowDay, nowDayOfWeek)
            this.weekFormat = weekStart + '~' + weekEnd
            console.log(this.weekFormat)
        },
        // 获得某一周的开始日期
        getWeekStartDate(nowYearnowMonthnowDaynowDayOfWeek) {
            let weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek)
            return this.formatDate(weekStartDate)
        },
        // 获得某一周的结束日期
        getWeekEndDate(nowYearnowMonthnowDaynowDayOfWeek) {
            let weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek))
            return this.formatDate(weekEndDate)
        }

 

 

posted @ 2019-11-01 11:21  傲气中华  阅读(6020)  评论(0编辑  收藏  举报