原创声明:本文为作者原创,未经允许不得转载,经授权转载需注明作者和出处
做项目的时候后台传到前台的时间格式都是时间戳,要是前台直接显示时间的话略显普通,若是将其转换成多久以前的发表的会不会觉得更好些呢?
微信小程序俱乐部
:附上小程序时间戳转换效果图
:<view class="v_beforetime">转换前:{{time}}</view>
<view class="v_aftertime">转换后:{{aftertime}}</view>
<button class="btn_changeTimestamp" bindtap="changeTimestamp"> 转换 </button>
.page{
height: 100%;
width: 100%;
}
.btn_changeTimestamp{
width:400rpx;
height:100rpx;
margin-top: 20rpx;
background:#0099FF;
}
.v_beforetime{
margin-top: 20rpx;
background:#C0C0C0;
}
.v_aftertime{
margin-top: 20rpx;
background:#FF0000;
}
// 时间戳转换成刚刚、几分钟前、几小时前、几天前
//刚刚
var just = new Date().getTime();
//几分钟前
var afewminutesago = new Date("Nov 29, 2016 00:50:00").getTime();
//几周前
var afewweekago = new Date("Nov 29, 2016 00:50:00").getTime();
//几年前
var someday = new Date("Nov 21, 2012 01:15:00").getTime();
var helloData = {
time: afewweekago
}
function getDateDiff(dateTimeStamp){
var result;
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var halfamonth = day * 15;
var month = day * 30;
var now = new Date().getTime();
var diffValue = now - dateTimeStamp;
if(diffValue < 0){
return;
}
var monthC =diffValue/month;
var weekC =diffValue/(7*day);
var dayC =diffValue/day;
var hourC =diffValue/hour;
var minC =diffValue/minute;
if(monthC>=1){
if(monthC<=12)
result="" + parseInt(monthC) + "月前";
else{
result="" + parseInt(monthC/12) + "年前";
}
}
else if(weekC>=1){
result="" + parseInt(weekC) + "周前";
}
else if(dayC>=1){
result=""+ parseInt(dayC) +"天前";
}
else if(hourC>=1){
result=""+ parseInt(hourC) +"小时前";
}
else if(minC>=1){
result=""+ parseInt(minC) +"分钟前";
}else{
result="刚刚";
}
return result;
};
Page({
data: helloData,
changeTimestamp: function (e) {
var that = this;
this.setData({
aftertime: getDateDiff(that.data.time)
})
}
})
`