Reputation: 3430
I have already tried out this question but it didn't solve my question.
I have a PHP server which sends a date via JSON to the user where it is then processed by Javascript:
PHP: 'date' => date('D M d Y H:i:s O', strtotime($array['Time']))
Javascript var time = new Date(data.date).toLocaleString()
But instead of getting 18. January 2015 ..., I get 3. March 5877521 -596:-31:-23 GMT+0:53:28. What is wrong there?
Some things you might need to know: The server has the central european timezone as well as the date sent. I am trying (above is only an example) to internationalize the date with javascript.
Upvotes: 0
Views: 324
Reputation: 17453
First, note that this error is quite common on the web, common enough that it's not [just] a "you" problem.
The reason for the weird March date millions of years in the future seems to be a bug in specific JavaScript engines. I noticed the same date appeared when some tests of ours were run in Chutzpah, a Jasmine test runner for Windows, when our test had an invalid date cast to a locale string and we ran only on its embedded setup from the command line (aka, not in a separate browser).
For our case, it turns out it was PhantomJS that was causing the issue. (PhantomJS used WebKit as its engine. I'd imagine your issue was from an engine with a similar lineage.)
Here's a minimal example that causes the error:
in a file called phantonTest.js
console.log(new Date('').toLocaleString('en-us', { timeZoneName: 'short' }));
phantom.exit();
then execute it...
>phantomjs.exe phantomTest.js
March 3, 5877521 at -8:-31:-23 GMT-4:56:02
You get a slightly date, but are performing a similar operation. You likely have an invalid date coming from strtotime($array['Time'])
and the user a similar browser engine. QED, etc.
Upvotes: 0
Reputation: 3430
I had to parse the timestamp as in Marc B's answer into an int (why ever?):
I solved it now: new Date(parseInt(data.date))
works
Upvotes: 0
Reputation: 360602
Why pass a string? JS's date constructor will accept a timestamp:
var time = new Date(<?php echo strtotime($array['Time']) ?>000);
Note the 000
in there. JS uses milliseconds, while strtotime
returns in seconds, so effectively you'd be building:
var time = new Date(12345678000);
^^^^^^^^---seconds from php
^^^---instant conversion to milliseconds.
Upvotes: 5