245

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

Roland
  • 9,321
  • 17
  • 79
  • 135
  • 2
    Order of operations is key. – Dylan Cross Dec 15 '12 at 17:49
  • 1
    So you'd like to have a timestamp, add 15 seconds, and then see what the difference is in seconds. I'd say the odds are high that the difference will be .... wait for it .... 15 seconds ? – adeneo Dec 15 '12 at 17:55
  • See also: http://stackoverflow.com/questions/13893754 – Tomasz Nurkiewicz Dec 15 '12 at 17:57
  • @adeneo ~ I'm not sure I follow :) I set a time stamp ( inital ) and another time stamp ( final ) based on the initial one, I mean the initial + an amount of seconds. This is my main purpose, lastly I will also get the time difference between those two – Roland Dec 15 '12 at 17:59
  • 1
    I really do understand what you're trying to do (I think), but If you take new Date(), which is the unix time right now, add 15 seconds, and right away check the difference, the difference will be 15 seconds (minus the milliseconds it took to calculate), but I'm guessing your intention is to compare this in the future somehow. – adeneo Dec 15 '12 at 18:02
  • Exactly, get that in the future :) I mean, both those initial and final will be stored locally ( localstorage ), then a third time will come up into play, which would be the time it took the user to do something. And I need the difference between the (diff between the initial and final) and the third time. I hope you understand :) – Roland Dec 15 '12 at 18:07
  • 1
    I don't really get it, to prove my point, here's a working [**FIDDLE**](http://jsfiddle.net/LLKrt/) for your above example. If you're trying to figure out how long the user took to do something, you usually get the timestamp when the user starts the operation, and the timestamp when the user finished the operation, and compare those, and you know how long it took. What the heck is the 15 seconds for ? – adeneo Dec 15 '12 at 18:10
  • The 15 seconds it's a timer :) That changes depending on the level you'll be :) – Roland Dec 15 '12 at 18:12
  • Your Fiddle works @adeneo :) – Roland Dec 15 '12 at 18:15
  • Here's another quick example -> [**FIDDLE**](http://jsfiddle.net/LLKrt/4/) – adeneo Dec 15 '12 at 18:16
  • You should post your example @adeneo :) – Roland Dec 15 '12 at 18:33
  • @Roland - It's not really an answer, not that any of the posted answers are either, but if you figure something out, just post it as an answer yourself, and accept it. – adeneo Dec 15 '12 at 18:38

10 Answers10

485

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 day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.

For example in Luxon we would do t1.diff(t2, "seconds") which is beautiful.


Useful docs for this answer

Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
  • 19
    There is no need for *getTIme*, the Dates can be subtracted from each other as the *-* operator will coerce them to Numbers. – RobG Aug 22 '15 at 05:25
  • 8
    getTime is necessary if you use typescript it doesn't allow arithmetic operation between element other than any, number or enum – zaffaste Mar 10 '16 at 08:41
  • 1
    You can use `.valueOf()`, which is what the `-` operator would call in any case... – Heretic Monkey Oct 26 '16 at 15:20
  • 1
    how about if we need the hour / minute time differences as well...? Should I devided it by 60 or multiple of it...? @Juan – gumuruh Mar 15 '17 at 09:39
  • Please add new doubts as individual questions, but since this one would probably be closed as a duplicate, take a look here http://stackoverflow.com/questions/1322732/convert-seconds-to-hh-mm-ss-with-javascript – Juan Cortés Mar 15 '17 at 11:16
  • If you're using TypeScript you can also do `var seconds = (+endDate - +startDate) / 1000;` – Max Coplan Nov 18 '20 at 19:19
12

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);
  • Why are we doing a %60? – AnandShiva Mar 04 '21 at 07:11
  • @Anand Shiva This will limit the result to 0-59, because the remainder operator (%) returns the remainder of a division operation and `60 % 60 = 0`. – l3l_aze Aug 01 '21 at 07:19
  • 2
    Why should we limit the time between 0-59? We are trying to calculate the difference between two times in seconds. The difference between now and 5 mins from now is 300s. We don't try to tell it as 300%60 right... – AnandShiva Aug 02 '21 at 06:19
9

Below code will give the time difference in second.

import Foundation

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 );
balkaran singh
  • 2,754
  • 1
  • 17
  • 32
Gautam Rai
  • 2,445
  • 2
  • 21
  • 31
8
<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>
7

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);
Ajmal Hasan
  • 885
  • 11
  • 9
1

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;
Surya Singh
  • 139
  • 2
  • 11
1
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.

Gourab Paul
  • 11
  • 1
  • 2
0

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)

0
  const getTimeBetweenDates = (startDate, endDate) => {
  const seconds = Math.floor((endDate - startDate) / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  return { seconds, minutes, hours, days };
};
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 20 '22 at 07:50
-1

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);
Gilbert Cut
  • 113
  • 1
  • 12
  • 2
    Huh? `.getSeconds()` just returns the seconds portion of a date time. Pretend start time = 0 minutes 58 seconds. End time = 5 minutes, 02 seconds. Your code would respond with -56 seconds as the time duration, and that's a total fail. – zipzit Jan 07 '22 at 03:19