【JS】时间格式化,及时间加减

1,时间格式化

    Date.prototype.formatCode = function (formatStr = "yyyy-MM-DD HH:mm:ss") {
        const paddingZero = num => num >= 10 ? num : '0' + num;
        let str = formatStr;
        str = str.replace(/yyyy|YYYY/, this.getFullYear());
        str = str.replace(/MM/, paddingZero(this.getMonth() + 1));
        str = str.replace(/dd|DD/, paddingZero(this.getDate()));
        str = str.replace(/hh|HH/, paddingZero(this.getHours()));
        str = str.replace(/mm/, paddingZero(this.getMinutes()));
        str = str.replace(/ss/, paddingZero(this.getSeconds()));
        str = str.replace(/SS/, paddingZero(this.getMilliseconds()));
        return str;
    };

    // 2022-11-03 15:10:46
    console.log(new Date().formatCode())

2,时间类型转换

    // Thu Nov 03 2022 15:19:48 GMT+0800 (中国标准时间)
    new Date();

    // 时间戳, 1667460038789
    new Date().valueOf();

    // 时间戳转时间
    new Date(1667460038789);

    // 2022/11/3 15:21:37
    new Date().toLocaleString();

    // 当前时间加八个小时 Thu Nov 03 2022 23:23:47 GMT+0800 (中国标准时间)
    new  Date(new  Date().setHours(new  Date().getHours() +  8))

猜你喜欢

转载自blog.csdn.net/u013517229/article/details/127670959