美文网首页
js根据时间字符串修改为“刚刚”“一分钟前”“一小时前”

js根据时间字符串修改为“刚刚”“一分钟前”“一小时前”

作者: 前端新阳 | 来源:发表于2020-01-20 19:28 被阅读0次

    【参考】:https://blog.csdn.net/bigbear00007/article/details/80328607?utm_source=app

    【代码】:

    function getshowtime(createtime) {
      if(createtime){ 
          createtime = createtime.replace(/-/g, "/"); // 处理 ios 不兼容问题
      }
      let createTime = new Date(createtime);
      let createTimes = createTime.getTime();
      let nowTime = new Date();
      let nowTimes =nowTime.getTime();
      if(nowTimes < createTimes){
          return `现在时间之后`
      }
    
      let createYear = createTime.getFullYear();
      let nowYear = nowTime.getFullYear();
      let createMonth = createTime.getMonth();
      let nowMonth = nowTime.getMonth();
      let createDate = createTime.getDate();
      let nowDate = nowTime.getDate();
    
      if(createYear<nowYear){
          return `${nowYear-createYear}年前`
      } else {
          if(createMonth<nowMonth){
              return `${nowMonth-createMonth}月前`
          } else {
              if(createDate<nowDate){
                  if(nowDate-createDate==1){
                      return `昨天`
                  } else {
                      return `${nowDate-createDate}天前`
                  }
              } else {
                  // 当天 
                  let diffValue = nowTimes - createTimes;
                  if(diffValue/(1000*60*60)>=1){
                      return `${parseInt(diffValue/(1000*60*60))}小时前`
                  } else {
                      if(diffValue/(1000*60)>=1){
                          return `${parseInt(diffValue/(1000*60))}分钟前`
                      } else {
                          return `刚刚`
                      }
                  }
              }
          }
      }
    }
    
    module.exports = {
      getshowtime
    }
    

    相关文章

      网友评论

          本文标题:js根据时间字符串修改为“刚刚”“一分钟前”“一小时前”

          本文链接:https://www.haomeiwen.com/subject/hmxszctx.html