终于知道错到哪里啦,这里必须保证是string形式的。所以这里我写36263256253这段数字当然有问题啦,
方法1:
//js时间戳怎么转成日期格式开始
//如果是个位数就补零
var ultZeroize = function (v, l) {
var z = "";
l = l || 2;
v = String(v);
for (var i = 0; i < l - v.length; i++) {
z += "0";
}
return z + v;
};
//具有年月和时间 2016-12-23 12:23:10
var dateToStr = function (d) {
if (typeof (d) == "string") d = new Date(d * 1000);
return (d.getFullYear() + "-" + ultZeroize(d.getMonth() + 1) + "-" + ultZeroize(d.getDate()) + " " + ultZeroize(d.getHours()) + ":" + ultZeroize(d.getMinutes()) + ":" + ultZeroize(d.getSeconds()));
};
//只有年月没有时间 2016-12-23
var dateShort = function (d) {
if (typeof (d) == "string") d = new Date(d * 1000);
return (d.getFullYear() + "-" + ultZeroize(d.getMonth() + 1) + "-" +ultZeroize(d.getDate()));
}
//js时间戳怎么转成日期格式结束
alert(dateToStr(“1471340009”)); //弹出2016-12-23 12:23:10
alert(dateShort(“1471340009”)) 结果是2016-08-16
最近发现一个简单点的
方法2:
function formatDate(data) {
let now = new Date(data);
var year=now.getFullYear(); //取得4位数的年份
var month=now.getMonth()+1< 10 ? ('0' +(now.getMonth()+1)):now.getMonth()+1;
var date=now.getDate()< 10 ? ('0' +now.getDate()):now.getDate() ;
var hour=now.getHours()< 10 ? ('0' +now.getHours()):now.getHours();
var minute=now.getMinutes()< 10 ? ('0' +now.getMinutes()):now.getMinutes();
var second=now.getSeconds()< 10 ? ('0' +now.getSeconds()):now.getSeconds();
return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
}
formatDate(1600884300000) //"2020-09-24 02:05:00"