计算时间差

function ****ysisTime(time) {
      const _d1 = new Date();
      const dateDiffer = Math.abs(_d1.getTime() - time);
      //准换年
      const year = Math.floor(dateDiffer / (1000 * 60 * 60 * 24 * 365));
      //取余数
      const years = dateDiffer % (1000 * 60 * 60 * 24 * 365);
      //将余数转换成月
      const month = Math.floor(years / (1000 * 60 * 60 * 24 * 30));
      //将余数转换成天
      const day = Math.floor(years / (1000 * 60 * 60 * 24));
      //取余数
      const hours = years % (1000 * 60 * 60 * 24);
      //将余数转换小时
      const hour = Math.floor(hours / (1000 * 60 * 60));
      // console.log(year,month,day,hour);
      if (year > 0) {
        return year + "年前";
      } else if (month > 0) {
        return month + "个月前";
      } else if (day > 0) {
        return day + "天前";
      } else if (hour > 0) {
        return hour + "小时前";
      } else {
        return "1小时之前";
      }
}

计算时间差,并转换成多久多久前,几年前、几个月前、几天前、几小时前、一小时前

 

posted @ 2022-11-10 13:06  默永  阅读(22)  评论(0编辑  收藏  举报