封装时间

168 阅读1分钟

        Date.prototype.format = function (format) {
            var o = {
                "M+": this.getMonth() + 1, //month
                "d+": this.getDate(),    //day
                "h+": this.getHours(),   //hour
                "m+": this.getMinutes(), //minute
                "s+": this.getSeconds(), //second
                "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
                "S": this.getMilliseconds() //millisecond
            }
            if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
                (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o) if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
            return format;
        }


    获取当天时间

        var ddate = new Date().format("yyyy-MM-dd")
        console.log(ddate);

获取本月时间 2022-12-01------2022-12-30

        
        var start = new Date();
        var end = new Date();
        start.setDate(1)
        end.setDate((new Date(start.getTime() - 1000 * 60 * 60 * 24)).getDate());
        startTime = start.format("yyyy-MM-dd");
        endTime = end.format("yyyy-MM-dd");
        console.log(startTime, endTime);

获取整年时间 2022-12-01------2021-12-01

        var dateas = [new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 365), new Date()]
        console.log(dateas[0].format('yyyy-MM-dd'));
        console.log(dateas[1].format('yyyy-MM-dd'));