In practical applications, it is necessary to calculate the difference between two time points. Generally speaking, the difference between the current time and a specified time point is calculated, and sometimes it needs to be accurate to days, hours, minutes and seconds. , let’s briefly introduce how to achieve this effect.
Rendering:
From New Year:
The code is as follows:
<html> <head> <title>javascript计算时间差</title> <style type="text/css"> #thenceThen { font-size:2em; } </style> <script type="text/javascript"> function thenceThen() { var theTime="2014/5/4" var endTime=new Date(theTime); var totalSecs=(endTime-new Date())/1000; var days=Math.floor(totalSecs/3600/24); var hours=Math.floor((totalSecs-days*24*3600)/3600); var mins=Math.floor((totalSecs-days*24*3600-hours*3600)/60); var secs=Math.floor((totalSecs-days*24*3600-hours*3600-mins*60)); if(days!=0) { document.getElementById("thenceThen").innerHTML=days+"天"+hours+"小时"+mins+"分钟"+secs+"秒"; } else if(hours==0&&mins==0) { document.getElementById("thenceThen").innerHTML=secs+"秒"; } else if(hours==0&&mins!= 0) { document.getElementById("thenceThen").innerHTML=mins+"分钟"+secs+"秒"; } else if (hours!=0) { document.getElementById("thenceThen").innerHTML=hours+"小时"+mins+"分钟"+secs+"秒"; } } var clock; window.onload=function() { clock=setInterval("thenceThen()",500); } </script> </head> <body> <div id="thenceThen"></div> </body> </html>
The above code achieves the function we want. Here is a brief introduction to the implementation process of this effect.
1. Implementation principle:
The principle is very simple. It is to calculate the millisecond difference between two points in time, and then perform mathematical operations to obtain the corresponding days, hours, minutes and descriptions. The function is called once per second through the setInterval() function, and then the countdown is started. Effect.
2. Code comments:
1.function thenThen(){}, this function is used to calculate the time difference.
2.var theTime="2014/5/4", this variable is used to define a time point at which the time difference is to be calculated.
3.var endTime=new Date(theTime), create the current time object.
4.var totalSecs=(endTime-new Date())/1000, the difference between the two time objects is the millisecond difference between the two, and then divided by 1000 is the description of the difference.
5.var days=Math.floor(totalSecs/3600/24), calculate the number of days difference, pay special attention to the function of Math.floor() function, you can refer to related reading.
6.var hours=Math.floor((totalSecs-days*24*3600)/3600), calculate the number of hours difference.
The above is the sample code for calculating the time difference in javascript. I hope it will be helpful to everyone's learning.