代码敲得再六又怎么样...

JavaScript 时间格式化刚刚、几秒前、几分钟前、几小时前、几天前、几月前和几年前

76 2020-12-16 08:02:45
// 格式 2020-01-01-01 01:01:01
function parseTime(date_str){
  var dateStr = date_str.replace(/-/g, "/");
  var date= new Date(dateStr);
  var dateTimeStamp = date.getTime();
  var minute = 1000 * 60; 
  var hour = minute * 60;
  var day = hour * 24; 
  var halfamonth = day * 15; 
  var month = day * 30; 
  var year = month * 12;
  var now = (new Date()).getTime(); 
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    result = "刚刚";
  }
  var yearC = diffValue / year, monthC = diffValue / month, weekC = diffValue / (7 * day), dayC = diffValue / day, hourC = diffValue / hour, minC = diffValue / minute;
  if (yearC >= 1) {
    result = parseInt(yearC) + "年前";
  } else if (monthC >= 1) {
    result = parseInt(monthC) + "月前";
  } else if (weekC >= 1) {
    result = parseInt(weekC) + "周前";
  } else if (dayC >= 1) {
    result = parseInt(dayC) + "天前";
  } else if (hourC >= 1) {
    result = parseInt(hourC) + "小时前";
  } else if (minC >= 1) {
    result = parseInt(minC) + "分钟前";
  } else {
    result = "刚刚";
  }
  return result;
}