Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Epoch to date conversion in javascript giving wrong answer

Tags:

javascript

I am using Date to convert unix milliseconds epoch to a date.

So 1501783442 == Tuesday, 8 August 2017 12:35:57.

But javascript says its Sun Jan 18 1970 14:39:43 GMT+0530 (IST).

<p id="demo"></p>

<script>
  var d = new Date(1501783442);
  document.getElementById("demo").innerHTML = d;
</script>

Jsfiddle link.

Whats going on here?

like image 677
Pratik Deoghare Avatar asked Aug 12 '26 05:08

Pratik Deoghare


1 Answers

First of all, 1501783442 equals GMT: Thursday, August 3, 2017 6:04:02 PM according to https://www.epochconverter.com/.

Second of all, Unix uses seconds whereas Javascript uses milliseconds. So in order to convert, you must multiply by 1000, which then gives the correct result (corrected for the timezone that your browser lives in):

<p id="demo"></p>

<script>
  var d = new Date(1501783442 * 1000);
  document.getElementById("demo").innerHTML = d;
</script>
like image 123
Peter B Avatar answered Aug 14 '26 18:08

Peter B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!