根据时间获取 几分钟前,几小时前 ········
- 能够根据时间字符串获取 几分钟前,几小时前,几天前,几月前,几年前
- 时间格式
yyyy-MM-dd HH:mm:ss
(可以缺省),例如:2020-08-18
、 2020-08-19 9:
、2020-08-19 09:10
都是支持的
export const getFormatMsgTime = (stringTime) => {
let minute = 1000 * 60;
let hour = minute * 60;
let day = hour * 24;
let week = day * 7;
let month = day * 30;
let year = month * 12;
let time1 = new Date().getTime();
if(stringTime == null){
return;
}
stringTime = stringTime.replace(/-/g, '/');
let time2 = Date.parse(new Date(stringTime));
let time = time1 - time2;
let result = null;
if (time < 0) {
alert("-1");
} else if (time / year >= 1) {
result = parseInt(time / year) + "年前";
} else if (time / month >= 1) {
result = parseInt(time / month) + "月前";
} else if (time / week >= 1) {
result = parseInt(time / week) + "周前";
} else if (time / day >= 1) {
result = parseInt(time / day) + "天前";
} else if (time / hour >= 1) {
result = parseInt(time / hour) + "小时前";
} else if (time / minute >= 1) {
result = parseInt(time / minute) + "分钟前";
} else {
result = "刚刚发布!";
}
return result;
}
function getTimer(stringTime) {
let minute = 1000 * 60;
let hour = minute * 60;
let day = hour * 24;
let week = day * 7;
let month = day * 30;
let year = month * 12;
let time1 = new Date().getTime();
let time2 = Date.parse(new Date(stringTime));
let time = time1 - time2;
let result = null;
if (time < 0) {
alert("-1");
} else if (time / year >= 1) {
result = parseInt(time / year) + "年前";
} else if (time / month >= 1) {
result = parseInt(time / month) + "月前";
} else if (time / week >= 1) {
result = parseInt(time / week) + "周前";
} else if (time / day >= 1) {
result = parseInt(time / day) + "天前";
} else if (time / hour >= 1) {
result = parseInt(time / hour) + "小时前";
} else if (time / minute >= 1) {
result = parseInt(time / minute) + "分钟前";
} else {
result = "刚刚发布!";
}
return result;
}