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"/>
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?
How to calculate the difference between two datetimes ? Javascript
use Math.abs
if you would get a negative value (ie if you don't know if a
is lower then b
)
Date object is essentially a number and you can do mathematical operations with it without getting timestamp
var a = new Date('2018-01-17T21:18:00')
var b = new Date('2018-01-16T21:17:00')
console.log(a - b) // possible use
console.log(Math.abs(a - b)) // safe to use
console.log(Math.abs(b - a)) // safe to use
console.log(b - a) // not what you want
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 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
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 =)");
Getting the difference between 2 dates in Javascript in hours, minutes, seconds with UTC
In your code you have:
var date1 = new Date().getTime();
There's no need to use getTime in this case. But it is helpful to use meaningful variable names:
var now = new Date();
Then there's:
var date2 = new Date("05/29/2017").getTime();
Don't use the Date constructor (or Date.parse) to parse strings as it's mostly implementation dependent and inconsistent. If you have a specific date, pass values directly to the constructor.
Regarding "use UTC", that's a bit confusing as ECMAScript Date objects are UTC. They use the host timezone offset to calculate an internal UTC time value, and also to display "local" date and time values. The only way I can interpret "use UTC" is to use Date.UTC to create a date instance, e.g.:
var endDate = new Date(Date.UTC(2017,4,29)); // 2017-05-29T00:00:00Z
Now you can get the difference between then an now using:
var diff = endDate - now;
When trying to get the hours, minutes and seconds you have:
var seconds = diff / 1000;
var minutes = (diff / 1000) / 60;
var hours = minutes / 60;
That converts the entire difference to each of hours, minutes and seconds so the total time is about 3 times what it should be. What you need is just the components, so:
var hours = Math.floor(diff / 3.6e5);
var minutes = Math.floor(diff % 3.6e5) / 6e4);
var seconds = Math.floor(diff % 6e4) / 1000;
Putting it all together in one function:
function timeLeft() {
var now = new Date();
var endDate = new Date(Date.UTC(2017,4,29)); // 2017-05-29T00:00:00Z
var diff = endDate - now;
var hours = Math.floor(diff / 3.6e6);
var minutes = Math.floor((diff % 3.6e6) / 6e4);
var seconds = Math.floor((diff % 6e4) / 1000);
console.log('Time remaining to ' + endDate.toISOString() +
' or\n' + endDate.toString() + ' local is\n' +
hours + ' hours, ' + minutes + ' minutes and ' +
seconds + ' seconds');
}
timeLeft()
Related Topics
How to Sort an Object Array by Date Property
Detecting an Undefined Object Property
Loading Cross-Domain Endpoint With Ajax
Uploading Both Data and Files in One Form Using Ajax
Addeventlistener Calls the Function Without Me Even Asking It To
Why Does Changing an Array in JavaScript Affect Copies of the Array
JavaScript: Client-Side Vs. Server-Side Validation
Is There a Standard Function to Check For Null, Undefined, or Blank Variables in JavaScript
Is There a Cross-Browser Onload Event When Clicking the Back Button
JavaScript "New Array(N)" and "Array.Prototype.Map" Weirdness
Getting a Random Value from a JavaScript Array
What Does the Exclamation Mark Do Before the Function
Benefits of Using 'Object.Create' For Inheritance
Origin Is Not Allowed by Access-Control-Allow-Origin
How to Loop Through a Plain JavaScript Object With the Objects as Members