js獲取距離指定時間已經過去多久程式碼例項

admin發表於2017-04-17

分享一段程式碼例項,它實現了獲取當前時間距離之前一個時間點已經過去多久功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
html, body, p {
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
}
body {
  background-color: #eee;
}
#main {
  font-size: 40px;
  padding-top: 400px;
  text-align: center;
  color: red;
  font-weight: bold;
  text-shadow: 0 0 6px rgba(0,0,0,.2);
}
</style>
</head>
<body>
<p id="main">
  離2016年01月01日<span></span>
</p>
<script type="text/javascript">
function toDouble(num) {
  num >= 10 ? num = '' + num : num = '0' + num;
  return num;
}
var main = $$('main'),
  span = $$('main').getElementsByTagName('span')[0];
 
function timer(year, month, day, hour, minute, seconds, elem) {
  var hour = hour || 0,
    minute = minute || 0,
    seconds = seconds || 0;
  var endTime = new Date();
 
  endTime.setFullYear(parseInt(year)),
  endTime.setMonth(parseInt(month) - 1),
  endTime.setDate(parseInt(day)),
  endTime.setHours(parseInt(hour)),
  endTime.setMinutes(parseInt(minute)),
  endTime.setSeconds(parseInt(seconds));
  setTime();
  setInterval(function() {
    setTime()
  }, 1000);
  function setTime() {
    var startTime = new Date();
    var lengthTime = parseInt((startTime.getTime() - endTime.getTime()) / 1000);
    var lSeconds = parseInt(lengthTime % 60),
      lMinute = parseInt((lengthTime / 60) % 60),
      lHour = Math.floor((lengthTime / 3600) % 24),
      lDay = Math.floor(lengthTime / (24 * 3600));
    span.innerHTML=lDay+'天'+toDouble(lHour)+'小時'+toDouble(lMinute)+'分鐘'+toDouble(lSeconds)+'秒';
  }
 
}
function $$(id) {
  return document.getElementById(id);
}
timer(2016, 01, 01, 0, 0, 0, span);
</script>
</body>
</html>

相關文章