What's the Best Way to Calculate Date Difference in JavaScript

Get difference between 2 dates in JavaScript?

Here is one way:

const date1 = new Date('7/13/2010');const date2 = new Date('12/15/2010');const diffTime = Math.abs(date2 - date1);const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); console.log(diffTime + " milliseconds");console.log(diffDays + " days");

What's the best way to calculate date difference in Javascript

Use the Date object like so:

function DateDiff(var /*Date*/ date1, var /*Date*/ date2) {
return date1.getTime() - date2.getTime();
}

This will return the number of milliseconds difference between the two dates. Converting it to seconds, minutes, hours etc. shouldn't be too difficult.

How to calculate number of days between two dates?

Here is a quick and dirty implementation of datediff, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).

/**
* Take the difference between the dates and divide by milliseconds per day.
* Round to nearest whole number to deal with DST.
*/
function datediff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}

/**
* new Date("dateString") is browser-dependent and discouraged, so we'll write
* a simple parse function for U.S. date format (which does no error checking)
*/
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0] - 1, mdy[1]);
}

alert(datediff(parseDate(first.value), parseDate(second.value)));
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

Get time difference between two dates in seconds

The Code

var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;

Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.



The explanation

You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00



Rant

Depending on what your date related operations are, you might want to invest in integrating a library such as date.js or moment.js which make things so much easier for the developer, but that's just a matter of personal preference.

For example in moment.js we would do moment1.diff(moment2, "seconds") which is beautiful.



Useful docs for this answer

  • Why 1970?
  • Date object
  • Date's getTime method
  • Date's getDate method
  • Need more accuracy than just seconds?

Difference in Months between two dates in JavaScript

The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)

You can get the year, month, and day of month from a JavaScript date object. Depending on what information you're looking for, you can use those to figure out how many months are between two points in time.

For instance, off-the-cuff:

function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}

function monthDiff(d1, d2) {    var months;    months = (d2.getFullYear() - d1.getFullYear()) * 12;    months -= d1.getMonth();    months += d2.getMonth();    return months <= 0 ? 0 : months;}
function test(d1, d2) { var diff = monthDiff(d1, d2); console.log( d1.toISOString().substring(0, 10), "to", d2.toISOString().substring(0, 10), ":", diff );}
test( new Date(2008, 10, 4), // November 4th, 2008 new Date(2010, 2, 12) // March 12th, 2010);// Result: 16
test( new Date(2010, 0, 1), // January 1st, 2010 new Date(2010, 2, 12) // March 12th, 2010);// Result: 2
test( new Date(2010, 1, 1), // February 1st, 2010 new Date(2010, 2, 12) // March 12th, 2010);// Result: 1

How do I get the difference between two Dates in JavaScript?

In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression.

So to get the difference, just subtract the two dates.

To create a new date based on the difference, just pass the number of milliseconds in the constructor.

var oldBegin = ...
var oldEnd = ...
var newBegin = ...

var newEnd = new Date(newBegin + oldEnd - oldBegin);

This should just work

EDIT: Fixed bug pointed by @bdukes

EDIT:

For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime().

So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)

Difference between dates in JavaScript

By using the Date object and its milliseconds value, differences can be calculated:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.

You can get the number of seconds (as a integer/whole number) by dividing the milliseconds by 1000 to convert it to seconds then converting the result to an integer (this removes the fractional part representing the milliseconds):

var seconds = parseInt((b-a)/1000);

You could then get whole minutes by dividing seconds by 60 and converting it to an integer, then hours by dividing minutes by 60 and converting it to an integer, then longer time units in the same way. From this, a function to get the maximum whole amount of a time unit in the value of a lower unit and the remainder lower unit can be created:

function get_whole_values(base_value, time_fractions) {
time_data = [base_value];
for (i = 0; i < time_fractions.length; i++) {
time_data.push(parseInt(time_data[i]/time_fractions[i]));
time_data[i] = time_data[i] % time_fractions[i];
}; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute).
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.

If you're wondering what the input parameters provided above for the second Date object are, see their names below:

new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);

As noted in the comments of this solution, you don't necessarily need to provide all these values unless they're necessary for the date you wish to represent.

How to calculate number of days between two dates

http://momentjs.com/ or https://date-fns.org/

From Moment docs:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1

or to include the start:

a.diff(b, 'days')+1   // =2

Beats messing with timestamps and time zones manually.

Depending on your specific use case, you can either

  1. Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments).
  2. Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
  3. Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.


Related Topics



Leave a reply



Submit