Javascript date diff in seconds

How to Calculate the Difference between Two Dates in JavaScript

As mentioned in the Date Creation in JavaScript article, there are very few native date calculation functions in JavaScript. In fact, there are none other than to convert between local and UTC time. Left to their own devices, web developers have devised many ways of calculating date intervals, some of which are ingenious, while others are flawed or just plain wrong.

I’ve scoured the Internet for some of the very best date interval calculation formulas so that I may present them to you today in easy-to-use static Date functions. I hope you find them useful!

Adding and Subtracting from a Given Date

According to the documentation, Date setters expect an interval-appropriate value. The setDays() setter, for instance, expects a day from 1 to 31. But really, these ranges are nothing more than helpful recommendations because day values that lie outside of this range are rolled over/back into the next/preceding month(s). For example, attempting to assign a day of 30 to February causes the date to roll over into March:

var febDate = new Date(2010, 1, 14); //Month is 0-11 in JavaScript febDate.setDate(30); console.log(febDate.toDateString()); //displays Tue Mar 2 2010

The same roll over behavior occurs in all the other setters and even accounts for leap years:

var y2k = new Date(2000, 0, 1); y2k.setMonth(14); console.log('14 months after the new millenium is: ' + y2k.toDateString()); //displays Thu Mar 31 2001 var y2k = new Date(2000, 0, 1); y2k.setHours(-22); console.log('22 hours before the new millenium is: ' + y2k); //displays Fri Dec 31 1999 02:00:00 GMT-0500 (Eastern Standard Time)

The roll over behavior presents us with the means to easily apply date intervals by supplying them directly to the appropriate setter:

var y2k = new Date(2000, 0, 1); y2k.setDate(y2k.getDate() + 88); console.log('88 days after the new millenium is: ' + y2k.toDateString()); //displays Wed Mar 29 2000

Calculating the Difference between Two Known Dates

Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can’t just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date’s internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):

Date.daysBetween = function( date1, date2 ) < //Get 1 day in milliseconds var one_day=1000*60*60*24; // Convert both dates to milliseconds var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); // Calculate the difference in milliseconds var difference_ms = date2_ms - date1_ms; // Convert back to days and return return Math.round(difference_ms/one_day); >//Set the two dates var y2k = new Date(2000, 0, 1); var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate()); var today= new Date(); //displays 726 console.log( 'Days since ' + Jan1st2010.toLocaleDateString() + ': ' + Date.daysBetween(Jan1st2010, today));

The rounding is optional, depending on whether you want partial days or not.

Читайте также:  Unique page title - My Site

Converting Milliseconds to other Intervals

As long as you can calculate the number of milliseconds in an interval, you can come up with a number by dividing the total number of milliseconds by the number of milliseconds in the desired interval. What’s more, we can apply the modulus (%) operator to strip out that value to determine the next larger interval. The key is to always go from the smallest interval – milliseconds – to the largest – days:

Date.daysBetween = function( date1, date2 ) < //Get 1 day in milliseconds var one_day=1000*60*60*24; // Convert both dates to milliseconds var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); // Calculate the difference in milliseconds var difference_ms = date2_ms - date1_ms; //take out milliseconds difference_ms = difference_ms/1000; var seconds = Math.floor(difference_ms % 60); difference_ms = difference_ms/60; var minutes = Math.floor(difference_ms % 60); difference_ms = difference_ms/60; var hours = Math.floor(difference_ms % 24); var days = Math.floor(difference_ms/24); return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds'; >//Set the two dates var y2k = new Date(2000, 0, 1); var Jan1st2010 = new Date(y2k.getYear() + 10, y2k.getMonth(), y2k.getDate()); var today= new Date(); //displays "Days from Wed Jan 01 0110 00:00:00 GMT-0500 (Eastern Standard Time) to Tue Dec 27 2011 12:14:02 GMT-0500 (Eastern Standard Time): 694686 days, 12 hours, 14 minutes, and 2 seconds" console.log('Days from ' + Jan1st2010 + ' to ' + today + ': ' + Date.daysBetween(Jan1st2010, today));

A Simple dateDiff() Function

There is no reason to write a function for each date/time interval; one function can contain all of the required intervals and return the correct value for the one we want. In the following function, the datepart argument tells it what interval we are after, where ‘w’ is a week, ‘d’ a day, ‘h’ hours, ‘n’ for minutes, and ‘s’ for seconds:

// datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's' Date.dateDiff = function(datepart, fromdate, todate) < datepart = datepart.toLowerCase(); var diff = todate - fromdate; var divideBy = < w:604800000, d:86400000, h:3600000, n:60000, s:1000 >; return Math.floor( diff/divideBy[datepart]); > //Set the two dates var y2k = new Date(2000, 0, 1); var today= new Date(); console.log('Weeks since the new millenium: ' + Date.dateDiff('w', y2k, today)); //displays 625

A More Complete DateDiff() Function

Perhaps the above function looks like the Visual Basic function of the same name. In fact it is loosely based on it. I was planning on recreating it in its complete form for your enjoyment, but, thankfully someone has already beat me to it. That someone is Rob Eberhardt of Slingshot Solutions. It’s part of his excellent jsDate script. It’s free to use as long as you give credit where credit is due.

His function offers a lot of advantages over the simple one presented above. For starters, his can calculate the month interval, which cannot be done by dividing into the number of milliseconds since month lengths differ. It also supports setting the first day of the week to something other than Sunday. Finally, it adjusts for Daylight Savings Time, which affects intervals of a day (“d”) and larger:

Date.DateDiff = function(p_Interval, p_Date1, p_Date2, p_FirstDayOfWeek)< p_FirstDayOfWeek = (isNaN(p_FirstDayOfWeek) || p_FirstDayOfWeek==0) ? vbSunday : parseInt(p_FirstDayOfWeek); var dt1 = Date.CDate(p_Date1); var dt2 = Date.CDate(p_Date2); //correct Daylight Savings Ttime (DST)-affected intervals ("d" & bigger) if("h,n,s,ms".indexOf(p_Interval.toLowerCase())==-1)< if(p_Date1.toString().indexOf(":") ==-1)< dt1.setUTCHours(0,0,0,0) >; // no time, assume 12am if(p_Date2.toString().indexOf(":") ==-1)< dt2.setUTCHours(0,0,0,0) >; // no time, assume 12am > // get ms between UTC dates and make into "difference" date var iDiffMS = dt2.valueOf() - dt1.valueOf(); var dtDiff = new Date(iDiffMS); // calc various diffs var nYears = dt2.getUTCFullYear() - dt1.getUTCFullYear(); var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0); var nQuarters = parseInt(nMonths / 3); var nMilliseconds = iDiffMS; var nSeconds = parseInt(iDiffMS / 1000); var nMinutes = parseInt(nSeconds / 60); var nHours = parseInt(nMinutes / 60); var nDays = parseInt(nHours / 24); //now fixed for DST switch days var nWeeks = parseInt(nDays / 7); if(p_Interval.toLowerCase()=='ww') < // set dates to 1st & last FirstDayOfWeek var offset = Date.DatePart("w", dt1, p_FirstDayOfWeek)-1; if(offset)< dt1.setDate(dt1.getDate() +7 -offset); >var offset = Date.DatePart("w", dt2, p_FirstDayOfWeek)-1; if(offset) < dt2.setDate(dt2.getDate() -offset); >// recurse to "w" with adjusted dates var nCalWeeks = Date.DateDiff("w", dt1, dt2) + 1; > // return difference switch(p_Interval.toLowerCase()) < case "yyyy": return nYears; case "q": return nQuarters; case "m": return nMonths; case "y": // day of year case "d": return nDays; case "w": return nWeeks; case "ww":return nCalWeeks; // week of year case "h": return nHours; case "n": return nMinutes; case "s": return nSeconds; case "ms":return nMilliseconds; default : return "invalid interval: '" + p_Interval + "'"; >> var y2k = new Date(2000, 0, 1) //Month is 0-11 in JavaScript! var today= new Date(); console.log('Months since the new millenium: ' + Date.DateDiff('m', y2k, today)); //displays 143

Conclusion

All of these date calculations have been leading up to the final leg of this short series where we’ll be creating a form to calculate annualized returns of capital gains and losses. It will feature the new HTML5 Date Input control, as well as a jQuery widget fallback. But first, we will be creating some specialized functions to deal with leap years.

Читайте также:  Storage classes in java

About the Author

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleConsulting.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob to receive a free estimate on your software project. Should you hire Rob and his firm, you’ll receive 15% off for mentioning that you heard about it here!

Источник

How to get the number of seconds between two Dates in JavaScript?

In this tutorial, we will learn how to get the number of seconds between two dates with JavaScript.

There are different methods for checking the number of days, hours, and seconds that are commonly used to provide information related to data. Since you can’t manually change the count of the years and months, we follow some simple tricks to get the number in JavaScript.

Using the Date getTime() Method

In JavaScript, we use different methods to calculate the days, hours, and seconds. Most popular way to calculate the time is .getTime(). However, you will get the result in milliseconds and have to convert it into seconds through division.

Syntax

var x = new Date("Aug 12, 2022 19:45:25"); var y = new Date("Aug 14, 2022 19:45:25"); let seconds = Math.abs(x.getTime() - y.getTime())/1000;

Here x and y are two dates. We will use the getTime() to get the times in milliseconds of both dates. We take the absolute difference between the two times in milliseconds. Then, after subtracting the time in milliseconds, we will divide it by 1000.

Algorithm

  • STEP 1 − Create two dates using the new Date(). You can refer to the example for the format of a date.
  • STEP 2 − Use the .getTime() method to get the time in milliseconds of both dates.
  • STEP 3 − Subtract the old date from the recent date. Then, divide the output by 1000 to get the difference in seconds.
  • STEP 4 − Use the innerHTML method to check the number of seconds difference between the two dates
Читайте также:  Python двоеточие после переменной

Example 1

We have created both the dates manually using the new Date(). You can also use different methods to generate the date in JavaScript.

html> body> h4> Using i> .getTime() method /i> to get number of seconds between to dates. /h4> p id="date1"> /p> p id="date2"> /p> p id="seconds">Number of seconds between two dates: /p> script> var t1 = new Date("Aug 12, 2022 19:45:25"); var t2 = new Date("Aug 14, 2022 19:45:25"); var dif = Math.abs(t1.getTime() - t2.getTime()) / 1000; document.getElementById('date1').innerHTML = "First date: " + t1; document.getElementById('date2').innerHTML = "Second date: " + t2; document.getElementById('seconds').innerHTML += dif + " seconds"; /script> /body> /html>

Using the Math.abs() Method

Math.abs() is a method used to round the numbers to the nearest answer to avoid getting floating numbers. Hence, you can also use Math.round() method instead of Math.abs(). You can get the time difference using this method in milliseconds. The time can be converted in seconds by dividing the output by 1000.

Syntax

We will use the following syntax to get the time in milliseconds and convert it into seconds through the division method

let x = new Date(); let y = new Date(); let dif = Math.abs(x - y) / 1000;

Here, we find the number of seconds between two dates – x and y. We take the absolute difference between these two dates using the Math.abs() method. This difference is in milliseconds, so we divide by 1000 to convert it into seconds.

Example 2

In this example, there are more than 31 days of difference in both the dates. We kept the dates similar so that the output could also be checked in seconds manually.

html> head> title> Example - get seconds between two dates /title> head> body> h3> Get seconds between to dates using absolute difference of the dates /h3> p id="date1"> /p> p id="date2"> /p> p id="seconds">Number of seconds between two dates: /p> script> let date1 = new Date("Nov 25 2022 07:24:35"); let date2 = new Date(); var dif = Math.abs(date1 - date2) / 1000; document.getElementById('date1').innerHTML = "First date: " + date1; document.getElementById('date2').innerHTML = "Second date: " + date2; document.getElementById('seconds').innerHTML += dif; /script> /body> /html>

The methods like .getTime() and Math.abs() are commonly used in JavaScript. You can alternatively use the Math.round() method to get similar output.

Have a look at the below example.

Example 3

html> head> title> Example - get seconds between two dates /title> head> body> h3> Get seconds between to dates using Matth.round() method /h3> p id="date1"> /p> p id="date2"> /p> p id="seconds">Number of seconds between two dates: /p> script> let date1 = new Date("Nov 25 2022 07:24:35"); let date2 = new Date(); var dif = Math.round(date1 - date2) / 1000; document.getElementById('date1').innerHTML = "First date: " + date1; document.getElementById('date2').innerHTML = "Second date: " + date2; document.getElementById('seconds').innerHTML += dif; /script> /body> /html>

While getting the answers, you should ensure the time is converted in seconds because the output can also be in minutes or milliseconds. Hence, you can check the examples above to understand the best way to get the output in seconds.

Источник

Оцените статью