How to display a date as iso 8601 format with PHP

后端 未结 6 2106
遇见更好的自我
遇见更好的自我 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:37

    The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

    // In this form it leaves the date as it is without taking the current date as a reference
    $dt = new DateTime();
    echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
    // return-> 2020-05-14T13:35:55.191Z
    
    // In this form it takes the reference of the current date
    echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
    return-> 2020-05-14T13:35:55.191Z
    
    // Various examples:
    $date_in = '2020-05-25 22:12 03.056';
    $dt = new DateTime($date_in);
    echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
    // return-> 2020-05-25T22:12:03.056Z
    
    //In this form it takes the reference of the current date
    echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
    // return-> 2020-05-25T14:22:05.188Z
    

提交回复
热议问题