js时间格式化几分钟前、几小时前

时间格式化几分钟前、几小时前
当前时间:2019-07-29 10:21:00

//打印
console.log(app.getDateDiff('2019-07-29 10:20:00'))
//输出  1分钟前
console.log(app.getDateDiff('2019-07-28 12:20:00'))
//输出  22小时前

app.js

// 时间格式化一分钟前、几天前
  // time 2018-05-25 18:14:02
  getDateDiff: function(time) {
    // 当前时间
    var nowTime = new Date();
    var day = nowTime.getDate();
    var hours = parseInt(nowTime.getHours());
    var minutes = nowTime.getMinutes();
    // 传来time 2018-05-25 18:14:02 分解
    var timeday = time.substring(8, 10);
    var timehours = parseInt(time.substring(11, 13));
    var timeminutes = time.substring(14, 16);
    var d_day = Math.abs(day - timeday);
    var d_hours = hours - timehours;
    var d_minutes = Math.abs(minutes - timeminutes);
    if(d_day <= 1){
      switch(d_day){
        case 0:
          if(d_hours==0 && d_minutes > 0){
            return d_minutes + '分钟前';
          }else if(d_hours==0 && d_minutes==0){
            return '1分钟前';
          }else{
            return d_hours + '小时前';
          }
          break;
        case 1:
          if(d_hours<0){
            return (24+d_hours) + '小时前';
          }else{
            return d_day + '天前';
          }
          break;
      }
    }else if(d_day > 1 && d_day<10){
      return d_day + '天前';
    }else{
      return time;
    }
  },

你可能感兴趣的:(微信小程序-交互效果)