Home > Web Front-end > JS Tutorial > js implements countdown and time objects

js implements countdown and time objects

高洛峰
Release: 2017-01-04 09:45:53
Original
1421 people have browsed it

The JS code to implement the countdown effect is as follows:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>h
<style>
#box {
 width: 100%;
 height: 400px;
 background: black;
 color: #fff;
 font-size:40px;
 line-height:400px;
 text-align:center;
}
</style>
<script>
window.onload = function(){
 var oBox = document.getElementById(&#39;box&#39;);
 var oDate = new Date();//获取当前时间;
 oDate.setFullYear(2016,11,31);//自动进位;
 oDate.setHours(0,0,0,0);
 
 function countDown(){
  //未来时间戳减去现在时间的时间戳;
  var ms = oDate.getTime() - new Date().getTime();
 
  //毫秒转换成秒
  var oSec = parseInt(ms/1000);
 
  //秒转换成天
  var oDay = parseInt(oSec/86400);
 
  //不到一天剩下的秒数;
  oSec%=86400;
 
  //转换成小时
  var oHour = parseInt(oSec/3600);
 
  //不到一小时剩下的秒数;
  oSec%=3600;
 
  //转换成分钟
  var oMin = parseInt(oSec/60);
 
  //不到一分钟剩下的秒数;
  oSec%=60;
 
  oBox.innerHTML = &#39;距离2016年12月31日还有:&#39;+oDay+&#39;天&#39;+oHour+&#39;时&#39;+oMin+&#39;分&#39;+oSec+&#39;秒&#39;;
 } 
 countDown();
 setInterval(countDown,1000);
}
</script>
</head>
 
<body>
<div id="box">距离2016年12月31日还有:xx天xx时xx分xx秒</div>
</body>
</html>
Copy after login

The implementation effect is as follows:

js implements countdown and time objects

Timestamp: The number of milliseconds since January 1970: oDate.getTime(); //Don’t ask me why it is from January 1970 to the present! Go to Baidu!
Time object:

Get time:

var oDate = new Date();
oYear = oDate.getFullYear();
oMon = oDate.getMonth();
oDay = oDate.getDate();
oHou = oDate.getHours();
oMin = oDate.getMinutes();
oSec = oDate.getSeconds();
oWeek = oDate.getDay();
Copy after login

Set time:

oDate.setFullYear(年,月,日);
oDate.setMonth(月);
oDate.setDate(日);
oDate.setHours(时,分,秒,毫秒);
时间会自动进位;
Copy after login

That’s all, there are still many shortcomings , I hope everyone can provide more valuable opinions! Learn from each other! Learn from each other!

For more articles related to js implementation of countdown and time objects, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template