16

I need the epoch time in days. I've seen posts on how to translate it to date but none in days. I'm pretty bad with epoch time...how could I get this?

dman
  • 10,406
  • 18
  • 102
  • 201

1 Answers1

41

I need the epoch time in days

I'll interpret that you want the number of days since the epoch. The epoch itself is day zero (or the start of day 1, however you want to view it).

At the heart of a javascript Date object is a number of milliseconds since 1970-01-01T00:00:00Z. So to get the number of days from then to now you simply get the current time value and divide it by the number of milliseconds in one day:

var now = new Date();
var fullDaysSinceEpoch = Math.floor(now/8.64e7);

For 2012-10-05 you should get 15618. Not sure if it allows for leap seconds and such, but it should be close enough (within a few seconds) if the system clock is accurate.

It is only when reading values of a Date object (such as getHours() and toString()) that the timezone offset is applied to give local times.

Ali
  • 21,572
  • 15
  • 83
  • 95
RobG
  • 142,382
  • 31
  • 172
  • 209
  • 2
    We only add leap seconds every year or two, so it will be tens of thousands of years before there will be enough to affect this calculation. – Barmar Oct 05 '12 at 04:51
  • 6
    @Barmar—cool, but there might be a moment about midnight where the number of days is out by one. System clocks shouldn't be relied upon for such accuracy anyway. :-) – RobG Oct 05 '12 at 06:44
  • 5
    This doesnt work in GMT+8 Timezone - to get it working I had to use: (date.getTime() - date.getTimezoneOffset()*60000) / 8.64e7 – Brian Flynn May 23 '19 at 04:46
  • @BrianFlynn—then your idea of "working" is different to the OP. – RobG May 23 '19 at 09:52
  • 1
    @RobG - can you clarify what you mean by that? I am in GMT+8 If I use your code as is I get a result that is off by 1 day. I have to subtract 8 hours from my dates to get the correct number of days since the epoch. – Brian Flynn May 24 '19 at 07:35
  • 2
    @BrianFlynn—the OP wants epoch (UTC) days, not local days. ECMAScript dates are UTC, so dividing by ms/day gives UTC days. If you're at +8 hrs, then at zero hours UTC you're already at +8. At say 20:00 UTC you'll be at 04:00 the next day, so UTC whole days is zero, but your local whole days is 1. BTW, your minus timezone offset actually adds the offset, since in ECMAScript an offset of +8 hours is represented as -480 minutes, hence you're getting local days. I hope that makes sense. :-) – RobG May 25 '19 at 06:59
  • 1
    For those using TypeScript, you'll have to adjust like so: `var fullDaysSinceEpoch = Math.floor(now.getTime()/8.64e7)` – Willster Sep 22 '22 at 18:33