Sample code to share JavaScript computing time difference _javascript tips

Source: Internet
Author: User
Tags setinterval

In practical applications, it is necessary to calculate the gap between the two time points, generally calculate the current time and a specified point of time between the gap, and sometimes need to be accurate to days, hours, minutes and seconds, the following is a brief description of how to achieve this effect.

Effect Chart:

From the New Year:

The code is as follows:

 

The above code to achieve the function we want, the following is a brief introduction to the implementation of the effect of the process.
I. Principle of realization:
The principle is very simple, is to calculate the millisecond gap between the point of time, and then through the mathematical calculation of the corresponding days, hours, minutes and descriptions, through the setinterval () function called every second function, then is the first inverted meter effect.
Two. Code comments:
1.function Thencethen () {}, this function is used to calculate the time gap.
2.var thetime= "2014/5/4", this variable is used to define a point in time when you want to calculate the difference.
3.var endtime=new Date (thetime) to create the current time object.
4.var totalsecs= (endtime-new Date ())/1000, the difference between two time objects is the millisecond gap between them, and divided by 1000 is the description of the difference.
5.var Days=math.floor (TOTALSECS/3600/24), calculate the difference of days, pay special attention to the function of Math.floor (), can refer to the relevant reading.
6.var Hours=math.floor ((totalsecs-days*24*3600)/3600) to calculate the difference in the number of hours.

The above is the JavaScript computation time difference sample code, hoped for everybody's study to be helpful.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.