JS中Unix时间戳转换日期格式

时间:2021-11-07 02:20:58
<!doctype html>
<html>
<head>
<title>Unix时间戳转换成日期格式</title>
<script>
var a = FormatDateTime("/Date(1497232433000)/")
var b = FormatDateTime("1497232740000")
console.log(a);
//2017-06-12 09:53:53
console.log(b); //2017-06-12 09:59:00
alert(a);
alert(b);
/*
* Unix时间戳转换成日期格式 FormatDateTime("1497232433000")
* @param UnixTime Unix时间戳
* @return yyyy-MM-dd HH:mm:ss
*/
function FormatDateTime(UnixTime) {
var a = UnixTime.replace("/Date(", "").replace(")/", "");
var date = new Date(parseInt(a));
var y = date.getFullYear();
var m = date.getMonth() + 1;
m
= m < 10 ? ('0' + m) : m;
var d = date.getDate();
d
= d < 10 ? ('0' + d) : d;
var h = date.getHours();
h
= h < 10 ? ('0' + h) : h;
var minute = date.getMinutes();
var second = date.getSeconds();
minute
= minute < 10 ? ('0' + minute) : minute;
second
= second < 10 ? ('0' + second) : second;
return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};
</script>
</head>
<body>
</body>
</html>