3

I have been trying to calculate the exact time since a very specific date in history using Javascript.

The Date is Feb 24th 2008 17:30 GMT+0

I need help in calculating exact time passed down to the second using Javascript. Here is the previous date and the current date. I need help in calculating Hours, Minutes and Seconds since that date/time.

var previousDate = new Date("Sun Feb 24 2008 17:30:00 GMT+0");
var currentDate = new Date();
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

It's easy to calculate the milliseconds between two dates:

var millis = currentDate - previousDate;

From there you can calculate the seconds:

var seconds = Math.round(millis / 1000);

Calculation of minutes, hours, ... is straightforward (division by 60 or 60*60).

hgoebl
  • 12,637
  • 9
  • 49
  • 72
0

Parsing of date strings in javascript fraught. If you have a specific date, far better to avoid the built–in parser. If it's UTC, use Date.UTC to generate the time value.

Then just subtract from any other date to get the difference in milliseconds and convert to seconds, as hgoebi suggests.

var epoch = new Date(Date.UTC(2008,1,24,17,30));
console.log(epoch.toISOString());

console.log(`Seconds from epoch to now: ${(Date.now() - epoch)/1000|0}`);
RobG
  • 142,382
  • 31
  • 172
  • 209