一般我们获取时间的时候,后台返回给我们的是一个很长串的数字(比如1494225027666)
,我们应该怎样转换成我们前端看得懂的时间呢(比如05-08 23:12)
?
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,target-densitydpi=medium-dpi,initial-scale=1, maximum-scale=1">
<title></title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="container">
<span>{{dateStr(1498702792*1000)}}</span>
</div>
<script src="js/common.js"></script>
</body>
</html>
common.js
new Vue({
el:'#container',
data:{
},
methods:{
dateObject: function(timestamp) {
//var timestamp = Number(timestamp);
var time = new Date(timestamp);
var Y = time.getFullYear(); //年
var m = ('0' + (time.getMonth() + 1)).substr(-2); //月
var d = ('0' + time.getDate()).substr(-2); //日
var H = ('0' + time.getHours()).substr(-2); //时
var i = ('0' + time.getMinutes()).substr(-2); //分
var s = ('0' + time.getSeconds()).substr(-2); //秒
return {
'Y': Y,
'm': m,
'd': d,
'H': H,
'i': i,
's': s
}
},
daysDiffer: function(start_time, end_time) {
var start_date_obj = this.dateObject(start_time),
end_date_obj = this.dateObject(end_time);
var start_date_time = new Date(start_date_obj.Y, start_date_obj.m - 1, start_date_obj.d);
var end_date_time = new Date(end_date_obj.Y, end_date_obj.m - 1, end_date_obj.d);
var d_days = parseInt((start_date_time - end_date_time) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
return d_days;
},
/**
* 当天的时间显示为:hh:mm
昨天的时间显示为:昨天hh:mm
同一年里比昨天更早的时间显示为:MM-DD hh:mm
不同年份的时间显示为:YYYY-MM-DD hh:mm
* @param {Object} timestamp
*/
dateStr: function(timestamp) {
var date_obj = this.dateObject(timestamp);
var diff_days = this.daysDiffer(timestamp, (new Date().getTime()));
if(diff_days == 0) {
return date_obj.H + ':' + date_obj.i;
}
if(diff_days == -1) {
return '昨天' + date_obj.H + ':' + date_obj.i;
}
if(diff_days < -1 && date_obj.Y != this.dateObject(new Date().getTime()).Y) {
return date_obj.Y + '-' + date_obj.m + '-' + date_obj.d + ' ' + date_obj.H + ':' + date_obj.i;
} else {
return date_obj.m + '-' + date_obj.d + ' ' + date_obj.H + ':' + date_obj.i;
}
}
}
})
大家可以尝试一下哦!