Skip to content Skip to sidebar Skip to footer

Javascript - Find Seconds Between Two Mm-dd-yyyy Hh:mm:ss Formatted Dates?

I am trying to use two MM-dd-yyyy HH:mm:ss formatted dates to find the time in seconds between them. How do I go about doing this?

Solution 1:

Use Date.parse(...) to parse the dates to create a Date object.

With .valueOf() on the created object you get the epoch (milliseconds since January 1st 1970) of this date.

Do this with both dates and substract the numbers. The difference is the time in milliseconds between the dates. The rest should be clear :)

Edit:

Following discussion in comments, here is the more valid reference to Date object: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-date-constructor

Solution 2:

You should never parse date string using the Date constructor or Date.parse (which do the same thing), always manually parse the string. A library can help, but for specific formats, a parse function is pretty simple.

The format MM-dd-yyyy HH:mm:ss is not one that is specified as supported by ES5 or later, so it will fall back to implementation dependent heuristics. Some browsers may parse it as local or UTC, and some may allow out of range values and others not. Some may not parse it at all.

A simple parse function (that doesn't validate values) is below.

Adding validation requires a little more code, but if you are confident that the provided data is good then it's not required.

To find the difference in seconds between two dates, simply subtract one from the other (which gives the difference in milliseconds) and divide by 1,000.

functionparseMDYhms(s) {
  var b = s.split(/\D/);
  returnnewDate(b[2], b[0]-1, b[1], b[3], b[4], b[5]);
}

var d0 = parseMDYhms('01-18-2015 12:52:13');
var d1 = parseMDYhms('01-19-2015 15:23:21');

var diffSeconds = (d1 - d0) / 1000;

document.write('Difference: ' + diffSeconds + ' seconds');

Post a Comment for "Javascript - Find Seconds Between Two Mm-dd-yyyy Hh:mm:ss Formatted Dates?"