Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Javascript Date.now() returning the wrong date?

When tested in the Firefox Javascript console,

Date.now();

returns 1433959098918.

Googling "1433959098918 ms in years" returns 45.4404 years, which added to January 1st 1970 00:00:00 is May 8th, 2015. I have also tried

(new Date()).getTime();

which returns the same result. Am I miscalculating something and if not, why is Date.now() returning this result?

EDIT: Nevermind, my calculation was incorrect. I assumed that dates are 0 based and they are not.

like image 414
Iambrett3 Avatar asked Dec 10 '22 22:12

Iambrett3


2 Answers

Because the js timestamp is not the unix timestamp, the unix timestamp is in seconds not in miliseconds you need divided for 1000, you can remove the last 3 digits

1433959098918 -> 1433959098

This different format have a lot of problems if you don't know it. :)

like image 109
Raúl Martín Avatar answered Dec 24 '22 18:12

Raúl Martín


Right now:

(new Date()).getTime()

Gives me:

1433959813432 (or 45,4 years)

Which is correct. You made an error in your computation:

1433959813432 [ms] / 60 [s/m] / 60 [m/h] / 24 [h/d] / 365.25 [d/y]
= 45.439444489821786194133901183867 [y]

You need to count 365.25 days per year to include leapyears.

It's not perfect AT ALL but it's a good approximation.

Add 1970 years and you get:

2015.4394444898217861941339011839

Which is the year 2015 plus the rest, which is:

0.4394444898217861941339011839 [y] * 365.25 [d/y]

Or:

160.50709990740740740740740740742 days

Now, deduct 31 days for january, 28 for february, 31 march, 30 for april and 31 for may and you get:

9.5070999074074074074074074074218 days into june

Which is the 10th day june of 2015 (count from 0).

The rest is:

0.5070999074074074074074074074218 * 24 hours
= 12.170397777777777777777777778123 hours

Plus my timezone and DST and it's just on spot!

like image 34
pid Avatar answered Dec 24 '22 17:12

pid