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"/>
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 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)
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 =)");
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
Related Topics
Creating Object With Dynamic Keys
Surprised That Global Variable Has Undefined Value in JavaScript
How to Pass Variable into an Evaluate Function
Console.Log() Shows the Changed Value of a Variable Before the Value Actually Changes
Chrome: Timeouts/Interval Suspended in Background Tabs
How to Check If CSS Value Is Supported by the Browser
Vertical Centering Variable Height Image While Maintaining Max-Width/Height
Google Maps Not Rendering Completely on Page
How to Transition the Flex-Grow of a Flex Box to Produce an Animation
Html5 Video - Percentage Loaded
Padding or Margin Value in Pixels as Integer Using Jquery
How to Show Live Preview in a Small Popup of Linked Page on Mouse Over on Link
How to Use JavaScript Conditionally Like CSS3 Media Queries, Orientation
Programmatically Changing Webkit-Transformation Values in Animation Rules
How to Detect CSS3 Resize Events