How to display a date as iso 8601 format with PHP

后端 未结 6 2092
遇见更好的自我
遇见更好的自我 2020-11-27 17:02

I\'m trying to display a datetime from my MySQL database as an iso 8601 formated string with PHP but it\'s coming out wrong.

17 Oct 2008 is coming out as: 1969-12-31

6条回答
  •  情深已故
    2020-11-27 17:31

    Procedural style :

    echo date_format(date_create('17 Oct 2008'), 'c');
    // Output : 2008-10-17T00:00:00+02:00
    

    Object oriented style :

    $formatteddate = new DateTime('17 Oct 2008');
    echo $datetime->format('c');
    // Output : 2008-10-17T00:00:00+02:00
    

    Hybrid 1 :

    echo date_format(new DateTime('17 Oct 2008'), 'c');
    // Output : 2008-10-17T00:00:00+02:00
    

    Hybrid 2 :

    echo date_create('17 Oct 2008')->format('c');
    // Output : 2008-10-17T00:00:00+02:00
    

    Notes :

    1) You could also use 'Y-m-d\TH:i:sP' as an alternative to 'c' for your format.

    2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :

    echo date_format(date_create('17 Oct 2008 +0800'), 'c');
    // Output : 2008-10-17T00:00:00+08:00
    

    3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :

    echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
    // Output : 2008-10-16T18:00:00-04:00
    

提交回复
热议问题