Write in front:

As mentioned in the question, it is necessary to calculate the time difference. Although it is not too difficult, this requirement is often encountered in the project. I will sort it out here, hoping to sort it out as thoroughly as possible. Friends in need can make a reference, like you can point bozan, or pay attention to it, I hope to help you.

This post was originally posted on my blog:obkoro1.com

Time difference calculation principle:

GetTime () method

Method definition: The getTime() method returns the number of milliseconds since January 1, 1970.

Usually, we calculate the time difference by obtaining two time data, and then using getTime () method to return the time difference with fixed January 1, 1970 respectively. By converting the difference of returned milliseconds into time units, we get the time difference between the two times.

Start operation:

First you will have an initial string of time data, and then you will use new Date(your time data) to convert your data into a Date object.

    var t1="2017/08/28 04:56:38"; Var dateBegin = new Date(t1); //Mon Aug 28 2017 04:56:38 GMT+0800Copy the code

Time format

Here we need to pay attention to the backend of the time data format, such as the following two:

The first:"2017/08/28 04:56:38"// This format does not need to handle the second type:"The 2017-08-01 18:56:38"// This format needs to be processedCopy the code

Because the new Date() method can’t handle the second data, we need to convert the second data format to the first data format here.

     var t1="The 2017-05-12 00:13:53";
     var dateBegin = new Date(d1.replace(/-/g, "/")); The //replace method converts - to /Copy the code

I don’t know about you, but I’m going to mention this because the data we gave me on the back end is the second one.

Another time data:

Since it is a time difference, there must be two data, otherwise how to compare the two data, generally there will be a current time data.

var dateEnd = new Date(); // Current time dataCopy the code

Complete calculation of time difference (days, hours, minutes, seconds) code:

Take the millisecond difference and use it to calculate the time you need. Then use the multiple relationship between the time units to calculate the time units.

functionVar dateBegin = new Date(d1.replace(/-/g)); var dateBegin = new Date(d1.replace(/-/g));"/")); Var dateEnd = new Date(); Var dateDiff = dateend.getTime () - datebegin.gettime (); Var dayDiff = math.floor (dateDiff/(24 * 3600 * 1000)); Var leave1=dateDiff%(24*3600*1000) var hours= math.floor (leave1/(3600*1000)) var hours= math.floor (leave1/(3600*1000) Var minutes= math.floor (leave2/(60*1000)) var minutes= math.floor (leave2/(60*1000)) var Leave3 =leave2%(60*1000) var seconds= math.round (leave3/1000) console.log("Difference"+dayDiff+"Day"+hours+"Hour"+minutes+"Minutes"+seconds+"Seconds")
    console.log(dateDiff+"Milliseconds of time difference",dayDiff+"Calculate the difference in days.",leave1+"Number of milliseconds remaining after counting days"
        ,hours+"Count the hours.",minutes+"Calculate the difference in minutes",seconds+"Calculate the difference in seconds");
}
var t3="The 2017-08-18 04:56:38";
timeFn(t3);Copy the code

Demo Time difference data screenshot

Immature month or year of calculation:

// dayDiff = dayDiff = dayDiffletmonthDiff=Math.floor(dayDiff/30); // Using 30 days as a month is not precise enough // get the month differenceif (monthDiff<12){
        timeThis=monthDiff+"Released a month ago."; // Get the month differencereturn
      }
      letyearDiff=Math.floor(monthDiff/12); // Get the year of the differenceif(yearDiff>=1){
        timeThis=yearDiff+"Released years ago.";
        return
      }Copy the code

When there is a big difference in the number of days, the simple calculation of days can no longer meet the requirements, because our PM said that 30 days should be used as the dividing line of a month, and the calculation of months here felt very complicated and we did not continue our research.

Gets the number of days in the current month

    function getDaysVar date = new date (); var year = date.getFullYear(); Var mouth = date.getMonth() + 1; // Get the current month var days; // Define the number of days in the month;if(mouth == 2) {days = year % 4 == 0? (mouth == 2) {days = year % 4 == 0? 29:28; }else if(expressions using = = 1 | | expressions using = = | 3 | expressions using = = 5 | | expressions using = = 7 | | expressions using = = 8 | | expressions using = = 10 | | expressions using = = 12) {/ / month for: 1,3,5,7,8,10,12 is the big moon. The number of days is 31; days = 31; }else{// Other months, days: 30. days = 30; }return days;
   }Copy the code

I found a function on the Internet to get the number of days in the current month, and the comments above are full enough, so I posted them together, linked below.

The latter

The above is the content of this article to calculate the time difference, I hope that after reading this article can give you a little help. One final tip: you’ll probably not have just one or two pieces of data to process. You’ll probably be given an array, and you’ll need to process time data forEach element of the array. In this case, forEach() is recommended to traverse the entire array.

Finally: if need to reprint, please put the original link and signature. Code word is not easy, thank you for your support! I write articles in line with the mentality of exchange records, write bad place, do not quarrel, but welcome to give directions. Then is the hope of watching the friends point a like, can also pay attention to me. Blog site and nuggets personal homepage

The above 2017.10.15

References:

Js Calculation time difference (day, hour, minute, second)