1

I path php datetime object by ajax.

Now I could get like this in javascript.

{"timezone":{"name":"Asia\/Tokyo","location":{"country_code":"JP","latitude":35.65231,"longitude":139.74232,"comments":""}},"offset":32400,"timestamp":1472655600}

how can I change this into javascript date object.

At first, parse date,

myDate  = JSON.parse(myDate||"null"); 
console.log(myDate);

then I can get consolelog like this.

{timezone: {…}, offset: 32400, timestamp: 1472655600}
aofdev
  • 1,772
  • 1
  • 15
  • 29
whitebear
  • 11,200
  • 24
  • 114
  • 237

1 Answers1

1

Should be super easy because you just mutltiply PHP's epoch time by 1000:

var str = '{"timezone":{"name":"Asia\/Tokyo","location":{"country_code":"JP","latitude":35.65231,"longitude":139.74232,"comments":""}},"offset":32400,"timestamp":1472655600}';

var myDate  = JSON.parse(str||"null"); 

var date = new Date(myDate['timestamp'] * 1000);

alert(date);

If you need to adjust the timezone though, you probably need an external library like moment.js. If that's the case, look at this: Convert date to another timezone in JavaScript . That said, if you're getting the timezone from PHP, and if you need to modify the datetime, it would be way easier to do it before you send your response.

Brian Gottier
  • 4,522
  • 3
  • 21
  • 37
  • Thank you very much. I understood the system of timestamp, as you mentioned, it is better to change DateTime to string in php in my case. but your explanation is quite great and helpful for javascript case. – whitebear Aug 28 '17 at 02:30