JS代码段:返回yyyy-mm-dd hh:mm:ss

时间:2023-03-08 23:14:33
JS代码段:返回yyyy-mm-dd hh:mm:ss

最近做项目的时候正好用到,本着能抄就抄的心态去百度搜索现成的代码,

没想到抄下来的好几个都是错的,要么getMonth没有加1,要么10以下的数字前面没有加0,

我真是日了狗了,这次把写好的正确的直接贴到博客里,以后直接去自己博客里面抄

getNowFormatDate: function() {
var date = new Date();
var Y = date.getFullYear() + "-";
var M =
(date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1) + "-";
var D =
date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " ";
var h =
date.getHours() < 10
? "0" + date.getHours() + ":"
: date.getHours() + ":";
var m =
date.getMinutes() < 10
? "0" + date.getMinutes() + ":"
: date.getMinutes() + ":";
var s =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return Y + M + D + h + m + s;
}