美文网首页工作生活
JS日期封装,获取本年、本月、本周日期

JS日期封装,获取本年、本月、本周日期

作者: namecho | 来源:发表于2019-07-02 17:51 被阅读0次
let date = {
    // 本年
    getThisYear() {
        const dateObj = new Date();
        let year = dateObj.getFullYear();
        let month = dateObj.getMonth() + 1;
        month = month > 9 ? month : '0' + month;
        let date = dateObj.getDate();
        date = date > 9 ? date : '0' + date;
        return [`${year}-01-01`, `${year}-${month}-${date}`];
    },
    // 本月
    getThisMonth() {
        const dateObj = new Date();
        let year = dateObj.getFullYear();
        let month = dateObj.getMonth() + 1;
        month = month > 9 ? month : '0' + month;
        let date = dateObj.getDate();
        date = date > 9 ? date : '0' + date;
        return [`${year}-${month}-01`, `${year}-${month}-${date}`];
    },
    // 本周
    getThisWeek() {
        const dateObj = new Date();
        let year = dateObj.getFullYear();
        let month = dateObj.getMonth() + 1;
        month = month > 9 ? month : '0' + month;
        let date = dateObj.getDate();
        date = date > 9 ? date : '0' + date;
        let time = dateObj.getTime();
        let day = dateObj.getDay();
        dateObj.setTime(time - 1000 * 60 * 60 * 24 * day);
        let dayYear = dateObj.getFullYear();
        let dayMonth = dateObj.getMonth() + 1;
        dayMonth = dayMonth > 9 ? dayMonth : '0' + dayMonth;
        let dayDate = dateObj.getDate();
        dayDate = dayDate > 9 ? dayDate : '0' + dayDate;
        return [`${dayYear}-${dayMonth}-${dayDate}`, `${year}-${month}-${date}`];
    }
}

返回格式

本年:["2019-01-01", "2019-07-02"]
本月:["2019-07-01", "2019-07-02"]
本周:["2019-06-30", "2019-07-02"]

相关文章

网友评论

    本文标题:JS日期封装,获取本年、本月、本周日期

    本文链接:https://www.haomeiwen.com/subject/vgpthctx.html