JavaScript 日期格式化方法

Jackey 其他 816 次浏览 , 没有评论
function format(date, format = "yyyy-MM-dd hh:mm:ss") {
    //new Date 在 ios safari浏览器有兼容性问题处理如下:
    // ? 兼容safari : 兼容其他浏览器
    let $this = new Date(date) == 'Invalid Date' ? new Date(date.substr(0, 19)) : new Date(date);

    let o = {
        'M+': $this.getMonth() + 1,
        'd+': $this.getDate(),
        'h+': $this.getHours(),
        'm+': $this.getMinutes(),
        's+': $this.getSeconds(),
        'q+': Math.floor(($this.getMonth() + 3) / 3),
        'S': $this.getMilliseconds()
    };
    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;
}

// 调用方法
// 默认格式
console.log(format(new Date()));
// 指定格式
console.log(format(new Date(), 'yyyyMMdd'));

参考来源:https://blog.csdn.net/qq_42673825/article/details/118458290

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Go