Skip to content

Instantly share code, notes, and snippets.

@viko16
Created August 20, 2014 17:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save viko16/542a11d98f983e98b9f5 to your computer and use it in GitHub Desktop.
Save viko16/542a11d98f983e98b9f5 to your computer and use it in GitHub Desktop.
人性化时间处理 #javascript
/**
* 格式化时间戳为人性化的时间
* @param {String} publishTime 时间戳
* @return {String} 人性化时间
*/
function formatTime(publishTime) {
var d_minutes, d_hours, d_days;
var timeNow = parseInt(new Date().getTime() / 1000, 10);
var d;
d = timeNow - publishTime;
d_days = parseInt(d / 86400, 10);
d_hours = parseInt(d / 3600, 10);
d_minutes = parseInt(d / 60, 10);
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) {
return "刚刚";
} else {
var s = new Date(publishTime * 1000);
return (s.getMonth() + 1) + "月" + s.getDate() + "日";
}
}
formatTime(1408556211); //6分钟前
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment