Get time difference between two dates in seconds

JavascriptDate

Javascript Problem Overview


I'm trying to get a difference between two dates in seconds. The logic would be like this :

  • set an initial date which would be now;
  • set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )
  • get the difference between those two ( the amount of seconds )

The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.

I've been trying something like this :

var _initial = new Date(),
	_initial = _initial.setDate(_initial.getDate()),
	_final = new Date(_initial);
	_final = _final.setDate(_final.getDate() + 15 / 1000 * 60);

var dif = Math.round((_final - _initial) / (1000 * 60));

The thing is that I never get the right difference. I tried dividing by 24 * 60 which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

Below code will give the time difference in second.

var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
    
alert(timeDiffInSecond );

Solution 6 - Javascript

time difference between now and 10 minutes later using momentjs

let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');

let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;

Solution 7 - Javascript

Define two dates using new Date(). Calculate the time difference of two dates using date2. getTime() – date1. getTime(); Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)

Solution 8 - Javascript

let startTime = new Date(timeStamp1);
let endTime = new Date(timeStamp2);

to get the difference between the dates in seconds ->

  let timeDiffInSeconds = Math.floor((endTime - startTime) / 1000);

but this porduces results in utc(for some reason that i dont know). So you have to take account for timezone offset, which you can do so by adding

> new Date().getTimezoneOffset();

but this gives timezone offset in minutes, so you have to multiply it by 60 to get the difference in seconds.

  let timeDiffInSecondsWithTZOffset = timeDiffInSeconds + (new Date().getTimezoneOffset() * 60);

This will produce result which is correct according to any timezone & wont add/subtract hours based on your timezone relative to utc.

Solution 9 - Javascript

try using dedicated functions from high level programming languages. JavaScript .getSeconds(); suits here:

var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds(); 

var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds(); 

alert(specifiedTimeSeconds-currentTimeSeconds);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRolandView Question on Stackoverflow
Solution 1 - JavascriptJuan CortésView Answer on Stackoverflow
Solution 2 - JavascriptGeorgian-Sorin MaximView Answer on Stackoverflow
Solution 3 - JavascriptAbdulrahman A AlkhodairiView Answer on Stackoverflow
Solution 4 - JavascriptAjmal HasanView Answer on Stackoverflow
Solution 5 - JavascriptGautam RaiView Answer on Stackoverflow
Solution 6 - JavascriptSurya SinghView Answer on Stackoverflow
Solution 7 - JavascriptSarath chandranView Answer on Stackoverflow
Solution 8 - JavascriptGourab PaulView Answer on Stackoverflow
Solution 9 - JavascriptGilbert CutView Answer on Stackoverflow