douzhi4830 2014-09-16 11:25
浏览 42
已采纳

从php获取日期到javascript

I am trying to get dates from PHP (I receive them from a database in the format 2014-09-16 22:00:00).

I then create an object in PHP because I have to work on those date in some occasions and I use:

$output[$i]['when'] = new DateTime($output[$i]['when'], new DateTimeZone('Europe/Brussels'));

Then I send that back in the javascript code with the following PHP command:

$line['when']->format('U')*1000

In fact, this line is in a foreach meaning that is the reason why you don't see a [$i].

My problem is that when going into javascript, it shows as 2 hours before. I am in CET and as I understand the format('U') means UTC. But I thought with specifying the datetimezone, this would work. How can I solve this? I know there is a 2 hours difference between CET and UTC so should I had that in milliseconds then * 1000 to have the microseconds?

EDIT: The 2 hours difference is only for some months, then it becomes 1 hour difference. I have then no idea how to solve this.

Thanks if you can help.

  • 写回答

1条回答 默认 最新

  • doukuiqian5345 2014-09-16 11:42
    关注

    Use a standard format that includes the timezone. The primary two you should use for the most straightforward javascript compatibility are RFC 2822 or ISO 8601. For this, let's use RFC 2822.

    So what you pass to your javascript should be the string returned from:

    $line['when']->format(\DateTime::RFC2822);
    

    There are constants on the DateTime class for various standard formats.

    Then in your javascript, you can do the following:

    var myDate = new Date('Tue, 16 Sep 2014 20:39:32 +0100');
    

    Which uses the RFC 2822 standard to parse the string into a new Date object, which you can then use as you would any other date object which should be in the correct timezone.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部