【问题标题】:How do I convert an ISO8601 date to another format in PHP?如何在 PHP 中将 ISO8601 日期转换为另一种格式?
【发布时间】:2011-09-21 11:06:31
【问题描述】:

Facebook 以 ISO8601 格式输出日期 - 例如: 2011-09-02T18:00:00

使用 PHP,我怎样才能重新格式化为: 2011 年 9 月 2 日星期五下午 6:00

Nb - 我是用 Javascript 做的,但是 IE 有日期错误,所以我想要一个跨浏览器的解决方案。

【问题讨论】:

    标签: php date datetime date-format datetime-format


    【解决方案1】:

    一个快速但有时不可靠的解决方案:

    $date = '2011-09-02T18:00:00';
    
    $time = strtotime($date);
    
    $fixed = date('l, F jS Y \a\t g:ia', $time); // 'a' and 't' are escaped as they are a format char.
    

    格式字符详解here

    【讨论】:

    • strtotime 是神奇的,但不是无所不知的。 '01-02-03' 可能会解析错误,因为它完全不明显是 Y、M 或 D。在这种情况下,日期字符串是一种有据可查的格式,因此不会成为问题。但是依靠 strtotime 永远正确是一种糟糕的方式。
    • 非常好 - 感谢您的帮助,马克
    • 在测试中 - 't' 还需要以 '\' 转义字符作为前缀。 (以防万一有人遇到同样的问题:-)
    【解决方案2】:

    从 ISO 8601 转换为 unixtimestamp :

    strtotime('2012-01-18T11:45:00+01:00');
    // Output : 1326883500
    

    从 unixtimestamp 转换为 ISO 8601(时区服务器):

    date_format(date_timestamp_set(new DateTime(), 1326883500), 'c');
    // Output : 2012-01-18T11:45:00+01:00
    

    从 unixtimestamp 转换为 ISO 8601 (GMT):

    date_format(date_create('@'. 1326883500), 'c') . "\n";
    // Output : 2012-01-18T10:45:00+00:00
    

    从 unixtimestamp 转换为 ISO 8601(自定义时区):

    date_format(date_timestamp_set(new DateTime(), 1326883500)->setTimezone(new DateTimeZone('America/New_York')), 'c');
    // Output : 2012-01-18T05:45:00-05:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-27
      相关资源
      最近更新 更多