先上效果圖
關鍵實現(xiàn)代碼如下:
/**
* @param str 指定的時間字符串踢俄,如yyyy-MM-dd HH:mm:ss
* */
function $GetFriendlyTime(str) {
var currentTime = new Date();
var arr = str.split(/\s+/gi);
var temp = 0, arr1, arr2, oldTime, delta;
var getIntValue = function (ss, defaultValue) {
try {
return parseInt(ss, 10);
} catch (e) {
return defaultValue;
}
};
var getWidthString = function (num) {
return num < 10 ? ("0" + num) : num;
};
if (arr.length >= 2) {
arr1 = arr[0].split(/[\/\-]/gi);
arr2 = arr[1].split(":");
oldTime = new Date();
oldTime.setYear(getIntValue(arr1[0], currentTime.getFullYear()));
oldTime.setMonth(getIntValue(arr1[1], currentTime.getMonth() + 1) - 1);
oldTime.setDate(getIntValue(arr1[2], currentTime.getDate()));
oldTime.setHours(getIntValue(arr2[0], currentTime.getHours()));
oldTime.setMinutes(getIntValue(arr2[1], currentTime.getMinutes()));
oldTime.setSeconds(getIntValue(arr2[2], currentTime.getSeconds()));
delta = currentTime.getTime() - oldTime.getTime();
if (delta < 0) {
delta = Math.abs(delta)
}
if (delta <= 60000) {
return "1分鐘內(nèi)";
}
else if (delta < 60 * 60 * 1000) {
return Math.floor(delta / (60 * 1000)) + "分鐘前";
}
else if (delta < 24 * 60 * 60 * 1000) {
return Math.floor(delta / (60 * 60 * 1000)) + "小時前";
}
else if (delta < 3 * 24 * 60 * 60 * 1000) {
return Math.floor(delta / (24 * 60 * 60 * 1000)) + "天前";
}
else if (currentTime.getFullYear() != oldTime.getFullYear()) {
return [getWidthString(oldTime.getFullYear()), getWidthString(oldTime.getMonth() + 1), getWidthString(oldTime.getDate())].join("-")
}
else {
return [getWidthString(oldTime.getFullYear()), getWidthString(oldTime.getMonth() + 1), getWidthString(oldTime.getDate())].join("-");
}
}
return "";
}