日期处理,“刚刚”,“2天前”的时间算法

这个逻辑算法是


function convertTime(timeStr) {
  var lastTime;

  if (typeof timeStr == "string") {
  if (!timeStr)
  return "";
  timeStr = timeStr.replace(/-/g, "/");

  lastTime = new Date(timeStr).getTime();
  }
  else if (typeof timeStr == "number")
  lastTime = timeStr;
  else if (typeof timeStr == "object")
  lastTime = Date.parse(timeStr);

  var nowTime = Date.parse(new Date()); //获取当前时间
  var timeLength = parseInt((nowTime - lastTime) / 1000);
  var str = 0;
  if (timeLength <= 60 * 3) {
  str = "刚刚";
  }
  else if (0 < timeLength && timeLength <= 60 * 5) {
  str = "5分钟前";
  }
  else if (0 < timeLength && timeLength <= 60 * 10) {
  str = "10分钟前";
  }
  else if (0 < timeLength && timeLength <= 60 * 15) {
  str = "15分钟前";
  } else if (60 * 15 < timeLength && timeLength <= 60 * 30) {
  str = "半小时前";
  } else if (60 * 30 < timeLength && timeLength <= 60 * 60) {
  str = "1小时前";
  } else if (60 * 60 < timeLength && timeLength <= 60 * 60 * 24) {
  str = parseInt(timeLength / 3600) + "小时前";
  } else if (60 * 60 * 24 < timeLength && timeLength <= 60 * 60 * 24 * 30) {
  str = parseInt(timeLength / 3600 / 24) + "天前";
  } else if (60 * 60 * 24 * 30 < timeLength && timeLength < 60 * 60 * 24 * 30 * 12) {
  str = parseInt(timeLength / 3600 / 24 / 30) + "月前";
  } else if (60 * 60 * 24 * 30 * 12 < timeLength) {
  str = parseInt(timeLength / 3600 / 24 / 30 / 12) + "年前";
  }
  return str;
}

猜你喜欢

转载自blog.csdn.net/mr_hexs/article/details/80321009