/**
* 格式化时间,1秒前,1分钟前 今天 10:11 昨天 10:11 9月11日 10:10
* @param {Date} date 时间对象
* @param {Date} currentDate 对比时间
* @return {String} 格式化后的时间内容
*/
var shortTime = function(date, currentDate) {
var now = currentDate,
// 今日秒数
todaySec = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds(),
secDiff = Math.floor( (now.getTime() - date.getTime()) / 1000 );
if(secDiff < 60) {
secDiff = secDiff < 1 ? 1 : secDiff;
return parseInt(secDiff) + '秒前';
}
if(secDiff <= 3600) {
return parseInt(secDiff / 60) + "分钟之前";
}
var h = ("0" + date.getHours()).slice(-2),
m = ("0" + date.getMinutes()).slice(-2),
d = date.getDate();
return ( now.getDate() == d && secDiff < 86400 ) ? ( "今天 " + h + ":" + m ) :
( secDiff >= todaySec && ( secDiff <= 86400 + todaySec ) ) ? ( "昨天 " + h + ":" + m ) :
( (date.getMonth() + 1) + "月" + d + "日 " + h + ":" + m );
};
//但一般我们会拿到一个"xxxx-xx-xx xx:xx:xx"的"发布时间",要相对当前时间格式化
var shortTime = function(date, currentDate) {
var pubtimeThis = date.split(" ");
var temp_a = pubtimeThis[0].split("-");
var temp_b = pubtimeThis[1].split(":");
date = new Date(temp_a[0], temp_a[1] - 1, temp_a[2], temp_b[0], temp_b[1]);
var now = currentDate || (new Date()),
// 今日秒数
todaySec = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds(),
secDiff = Math.floor( (now.getTime() - date.getTime()) / 1000 );
if(secDiff < 60) {
secDiff = secDiff < 1 ? 1 : secDiff;
return parseInt(secDiff) + '秒前';
}
if(secDiff <= 3600) {
return parseInt(secDiff / 60) + "分钟之前";
}
var h = ("0" + date.getHours()).slice(-2),
m = ("0" + date.getMinutes()).slice(-2),
d = date.getDate();
return ( now.getDate() == d && secDiff < 86400 ) ? ( "今天 " + h + ":" + m ) :
( secDiff >= todaySec && ( secDiff <= 86400 + todaySec ) ) ? ( "昨天 " + h + ":" + m ) :
( (date.getMonth() + 1) + "月" + d + "日 " + h + ":" + m );
};