当前时间与过去时间戳相减获取时间差(2020-06-17)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <script type="text/javascript">
      var time1 = '2020-06-09 19:31:51'
      var timestamp1 = Date.parse(new Date(time1))
      var timestamp2 = new Date().getTime()
  
      function diffTime(startDate, endDate) {
        var diff = endDate - startDate //时间差的毫秒数 
        var days = Math.floor(diff / (24 * 3600 * 1000)) //计算出天数
        var leave1 = diff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000)) //计算相差小时数
        var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
        console.log(days+ '天' + hours + '时' + minutes  + '分');
        if(days > 0) {
            return  days + '天前'
            // 小于天数
        }else{
            if(hours > 0) {
                return hours + '小时前'
            }else {
                if(minutes > 0) {
                    return minutes + '分钟前'
                }else {
                    return '刚刚'
                }
            }      
        }
      }
     console.log(diffTime(timestamp1, timestamp2))
    </script>
  </body>
</html>

你可能感兴趣的:(工作经验)