douzhi4830 2014-09-16 19: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 19: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.

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

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)