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?
You can use new Date().getTime()
for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms
into s
.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();
var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>
Accurate and fast will give output in seconds:
let startDate = new Date()
let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);