First, start
This Tuesday to interview encountered a topic such as "please use JS to achieve the distance xx and left ... Days...... Hours...... Seconds ", at the time just thought to create a data to save how many days each month, and then to get the number of days subtraction on it.
Just to solve this problem, and did not think about it, now feel that this method is too cumbersome, and there is a leap year problem.
Now I'm going to re-write this method and use the time stamp to solve the problem.
Second, time stamp
What is a timestamp? The time stamp is actually now the time from GMT January 01, 1970 00:00 00 seconds (Beijing time January 01, 1970 08:00 00 seconds) up to now the total number of seconds.
Note that there is a eight-hour error in time, so our direct new Date (2018-01-01) is actually the eight point of January 1, 2018, so we have to specify the timing.
Third, the realization
For example, we write a method to calculate how many days we have from 2018:
functionDatecount () {//get the time now varDate =NewDate (); //the first day of 2018 varUntil =NewDate (' 2018-01-01 00:00:00 ')); //An implicit conversion occurs during calculation, and the valueof () method is called to convert to a timestamp form varDays = (until-date)/1000/3600/24;//The following are simple mathematical calculations varDay =Math.floor (days); varHours = (days-day) *24; varhour =Math.floor (hours); varminutes = (hours-hour) *60; varminute =Math.floor (minutes); varseconds = (Minutes-minute) *60; varSecond =Math.floor (seconds); varback = ' distance 2018 Left ' +day+ ' +hour+ ' hours ' +minute+ ' minutes ' +second+ ' seconds '; returnBack ; }
And then use the SetInterval () method to achieve real-time reciprocal
SetInterval (function() { var text = datecount (); // Show is a node Show.innertext = text;},1000)
This achieves the reciprocal:
JS implementation Countdown-' How many days left '