简体   繁体   中英

javascript date from php unix timestamp

In database i have a row with date & time, say 2014-04-16 00:00:00 then I convert that datetime to unix timestamp using

strtotime('2014-04-16 00:00:00') * 1000; // result 1397577600000

In javascript i am trying to get the hour using the following code

var d = new Date(1397577600000); // 1397577600000 from php unix timestamp in previous code
d.getHours(); // return 23
d.getMinutes(); // return 0

why getHours() return 23 instead of 0? is there any difference between js timestamp and php timestamp?

Date objects in javascript will always return values based on the browser's current timezone. So if d.getHours() is returning 23 for you, that would suggest your local browser timezone is one hour earlier than UTC (-01:00).

It you want the hours for a Date object based on UTC timezone, you can use:

d.getUTCHours()

Follow Up:

Just to throw out some free advice, you could use the following code to deal with your date values from one context to another:

PHP:
 // Fetched from the db somehow $datetime_db = '2014-04-16 00:00:00'; // Convert to PHP DateTime object: $datetime_obj = new DateTime($datetime_db, new DateTimeZone('UTC')); // Format DateTime object to javascript-friendly ISO-8601 format: $datetime_iso = $datetime_obj->format(DateTime::W3C); 
Javascript:
 var d = new Date('2014-04-16T00:00:00+00:00'); // 2014-04-16T00:00:00+00:00 from PHP in previous code d.getUTCHours(); // returns 0 

This keeps the datetime variables in a language-specific object format when being handled in that language, and serializes the value into a string format that all current browsers/languages accept (the international standard ISO-8601).

我在这里得到21 ,因为在Javascript中,用户的本地时区将被视为获取时间和日期。

Ok, based on what Arun P Johnny said.

I change the strtotime parameter to match my timezone, in this case i changed it to

strtotime('2014-04-16 00:00:00 GMT+7') * 1000;

hope this help anybody that have the same problem as I.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM