How 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");

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).

// 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]);

}

function datediff(first, second) {

// Take the difference between the dates and divide by milliseconds per day.

// Round to nearest whole number to deal with DST.

return Math.round((second-first)/(1000*60*60*24));

}

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

<input id="second" value="1/1/2001"/>

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

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 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.

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)

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.

JavaScript - Get minutes between two dates

You may checkout this code:

var today = new Date();
var Christmas = new Date(today.getFullYear() + "-12-25");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas =)");


Related Topics



Leave a reply



Submit