js将时间转为刚刚,前天,昨天,今天

js将时间转为刚刚,前天,昨天,今天

js将时间转为刚刚,前天,昨天,今天。时间显示规则:

  • 发布3天内显示,今天/昨天/前天 + 具体时间,今天 16:30昨天 12:00前天 8:00
  • 发布超过3天显示,m-dd,例如 5-15
  • 发布超过一年显示,yyyy-mm-dd
  • 先来看看实现效果
js将时间转为刚刚,前天,昨天,今天
  • 接下来上js代码
zeroize: function (num) {
  return (String(num).length == 1 ? '0' : '') + num;
}
timestampFormat: function (timestamp) {
  var self = this;
  var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
  var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

  var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
  var tmDate = new Date(timestamp * 1000);  // 参数时间戳转换成的日期对象

  var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
  var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();

  if (timestampDiff < 60) { // 一分钟以内
    return "刚刚";
  } else if (timestampDiff < 3600) { // 一小时前之内
    return Math.floor(timestampDiff / 60) + "分钟前";
  } else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
    return '今天' + self.zeroize(H) + ':' + self.zeroize(i);
  } else {
    var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
    var newDate2 = new Date((curTimestamp - (86400 * 2)) * 1000); // 参数中的时间戳加俩天转换成的日期对象
    if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
      return '昨天' + self.zeroize(H) + ':' + self.zeroize(i);
    } else if (newDate2.getFullYear() == Y && newDate2.getMonth() + 1 == m && newDate2.getDate() == d) {
      return '前天' + self.zeroize(H) + ':' + self.zeroize(i);
    } else if (curDate.getFullYear() == Y) {
      return m + '-' + self.zeroize(d) + ' ' + self.zeroize(H) + ':' + self.zeroize(i);
    } else {
      return Y + '-' + self.zeroize(m) + '-' + self.zeroize(d) + ' ' + self.zeroize(H) + ':' + self.zeroize(i);
    }
  }
}
this.timestampFormat(new Date(item.CreatedAt).getTime() / 1000)

完成!!!

参考了:

https://www.cnblogs.com/taochengyong/p/9341986.html

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注