1

Lets say I have a date-time object 2015-12-31T12:59. Is there a way in JavaScript to find the difference between current date-time and the above date-time object in seconds? Basically, is there a way to find out the time in seconds from this very moment till the date-time specified by a future date-time object?

I did some digging but couldn't find anything that could be of any use for me in this case.

Manas Chaturvedi
  • 5,210
  • 18
  • 52
  • 104

1 Answers1

2

To achieve this you can simply subtract the date object from Date.now(). Then take the millisecond value that it gives you, and divide by 1000 to get the second value. Here is a live example:

var date1 = new Date("2015-12-31T12:59");
var date2 = Date.now();

document.getElementById("output").innerHTML = (date1 - date2) / 1000;
Seconds between now and (2015-12-31T12:59): <span id="output"></span>
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
  • Parsing strings with the Date constructor is recommended against because it is browser dependent. The string "2015-12-31T12:59" will be parsed to at least 3 different values by browsers in use. – RobG Aug 21 '15 at 21:54
  • @RobG Parsing strings with the Date constructor is well-defined across browsers if the date string is in the standard format, which it is. [See this answer](http://stackoverflow.com/a/4321366/2234742) for more details. – Maximillian Laumeister Aug 21 '15 at 22:17
  • That answer is simply wrong to state that there are strings "guaranteed to work". Prior to ES5, parsing was entirely implementation dependent. Some browsers from that era (e.g. IE8, which is still has about 20% user share) will return NaN. Browsers consistent with ES5 (including the most recent version of Firefox and fairly recent versions of other browsers) treat the string as UTC. Those consistent with ECMA 2015 (latest Safari, Chrome, etc.) will treat it as local. So "well defined", maybe. Consistent? No. – RobG Aug 22 '15 at 05:21