前言:date.format() 函数 ,请参照之前的文章
最好用的JS时间date操作类(时间格式化、加减日、月、年、操作)
<pre name="code" class="javascript">function getDate(timestamp) {
var date = new Date(timestamp);
return date.format("yyyy-MM-dd hh:mm:ss");
}
1.过去了多少时间(xx天xx小时xx分钟xx秒之前)
function timeago(timestamp) {
var d_minutes, d_hours, d_days, d_seconds;
var timeNow = parseInt(new Date().getTime() / 1000);
d_seconds = timeNow - timestamp / 1000;
d_days = parseInt(d_seconds / 86400);
d_hours = parseInt(d_seconds / 3600);
d_minutes = parseInt(d_seconds / 60);
if (d_days > 0 && d_days < 4) {
return d_days + "天前";
} else if (d_days <= 0 && d_hours > 0) {
return d_hours + "小时前";
} else if (d_hours <= 0 && d_minutes > 0) {
return d_minutes + "分钟前";
} else if (d_minutes <= 0 && d_seconds > 0) {
return d_seconds + "秒前";
} else {
return getDate(timestamp);
}
}
2.还剩多少时间结束(xx天xx小时xx分钟xx秒)
function timediff(timestamp) {
var d_minutes, d_hours, d_days, d_seconds, ret = "";
var timeNow = parseInt(new Date().getTime() / 1000);
d_seconds = timestamp / 1000 - timeNow;
if (d_seconds < 0) {
return -1;
}
d_days = parseInt(d_seconds / 86400);
d_hours = parseInt(d_seconds / 3600) - d_days * 24;
d_minutes = parseInt(d_seconds / 60) - d_days * 24 * 60 - d_hours * 60;
if (d_days > 0)
ret += d_days + "天";
if (d_hours > 0)
ret += d_hours + "时";
if (d_minutes > 0)
ret += d_minutes + "分";
return ret + (d_seconds - d_days * 24 * 60 * 60 - d_hours * 60 * 60 - d_minutes * 60) + "秒";
}