简体   繁体   中英

Does JavaScript Date object recognises the input datestring as UTC time or local time?

There are already quite a number of questions regarding time, but I still couldn't find one that can answer my question. So, I have to apologise if this is a repeat. My question is this:

I have a MySQL table column named postDate in datetime format. My server is on system time (UTC). I have the following php script:

<script type='text/javascript'>
 var expiry = new Date('$postDate');
 alert(expiry);
</script>

$postDate = date("r", strtotime($postDate)); // sorry forgot to add this line

I just want to know, assuming $postDate is 2012-03-30 01:00:00 , and the client is on a +8hr time zone, what will he see on the alert? Ie does JavaScript Date object recognises the datestring as UTC time or local time?

Depending on the user's locale, that will fail with the result "Invalid Date".

Instead, you should pass a timestamp. Timestamps are ALWAYS in UTC. To get a timestamp from your datetime format, run it through strtotime() . But bear in mind that JS does timestamps in milliseconds, not seconds, so you have to add an extra 000 to the end.

So basically:

$postDate = strtotime($postDate)."000";

The result of the alert will still depend on the user's timezone, but it will be correctly offset from the UTC timestamp you gave. For example, if the timestamp is 1AM UTC, but the user is in UTC+8, they will see 9AM.

在此输入图像描述 and yes, it does work , amazing. just 2 lines of code in a fiddle.

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