如何将日期Date转换为指定的格式:如 yyyy-MM-dd hh:mm:ss 或者 yyyy-MM-dd ?

可以为Date原型添加如下的方法:

Date.prototype.format = function(fmt) { 
     var 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(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}    

注意:Date原型上是没有format这个内置函数的,需要先对其进行扩展,再使用。可以将此段代码放到vue的mounted中,使用时直接在methods中使用即可。

使用示例:

yyyy-MM-dd hh:mm:ss

var time1 = new Date().format("yyyy-MM-dd hh:mm:ss");
console.log(time1); // 2022-01-18 15:20:39

yyyy-MM-dd

var time2 = new Date().format("yyyy-MM-dd");
console.log(time2);  // 2022-01-18

yyyy-MM-dd

var oldTime = (new Date("2022/1/18 15:26:11")).getTime(); // 1642490771000
var curTime = new Date(oldTime).format("yyyy-MM-dd");
console.log(curTime); // 2022-01-18

有关时间戳和Date相互转换的内容可以参考:【JS】获取当前时间戳以及计算时间差 +【AntDesign】时间日期控件计算差值踩坑

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐