<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>时间戳与展示时间互相转化</title>
</head>
<body>
<script type="text/javascript">
//参考获取当前时间戳
//http://blog.sina.com.cn/s/blog_8772845101019kg5.html
//http://tool.chinaz.com/tools/unixtime.aspx
//http://css.tools.chinaz.com/tools/js/jq-tools.js?v=201608
var timestamp = new Date().getTime();
function unix2human(timestamp) {
var now = new Date(timestamp);
var year = now.getFullYear();
var month = (now.getMonth() + 1) < 10 ? '0' + (now.getMonth() + 1) : (now.getMonth() + 1);
var date = 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;
}
//JavaScript UTC() 方法
//http://www.w3school.com.cn/jsref/jsref_utc.asp
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
function human2unix(year, month, day, hour, minute, second) {
year = year ? year : new Date().getFullYear(), month = month ? month : 1, day = day ? day : 1, hour = hour ? hour : (year == 1970 ? 0 : 0), minute = minute ? minute : 0, second = second ? second : 0;
//var humanDate = new Date(Date.UTC(year, month, day, hour, minute, second));
//var humanDate = new Date(year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second);
var humanDate = new Date(year, month, day, hour, minute, second);
return humanDate.getTime();
}
console.log('时间戳格式化后的时间>>>', unix2human(timestamp));
console.log('转输入时间的时间戳', human2unix(2017, 4, 27, 15, 2, 4) + '>>,' + unix2human(human2unix(2017, 4, 27, 15, 2, 4)));
</script>
</body>
</html>