skip to Main Content

I want to convert this date-time string 2022-09-30T21:39:25.220185674Z to yyyy-mm-dd hh:mm:ss but it returns 1970-01-01 01:00:00 everytime.

Tried with: date('Y-m-d H:i:s', strtotime('2022-09-30T21:39:25.220185674Z')); or date('Y-m-dTH:i:s', strtotime('2022-09-30T21:39:25.220185674Z'));

Can you help find out which format this is and how i could corretly format such string in PHP?

Went through this question or this one couldn’t help.

2

Answers


  1. It’s a ISO 8601 datetime string with microseconds, where Z is the timezone "Zulu" or UTC + 0 hours.

    ISO 8601 can be parsed with DateTime() like this:

    $string = '2022-09-30T21:39:25.220185Z';
      //create DateTime object
    $date   = date_create_from_format( "Y-m-dTH:i:s.uP" , $string);
    echo $date->format( 'Y-m-d H:i:s.u' );
    

    However This will not work with your string, as the u parameter in the format "Y-m-dTH:i:s.uP" which represents the microseconds, in PHP takes a maximum of 6 digits, and yours has 9.

    You can resolve this by removing all above 6 digits from the microseconds part of the string with a regex, like

    $string = '2022-09-30T21:39:25.220185674Z';
    $new_string = preg_replace( '/^.*?.d{0,6}Kd*/' , '' , $string );
    $date   = date_create_from_format( "Y-m-dTH:i:s.uP" , $new_string );
    echo $date->format('Y-m-d H:i:s.u');
    

    Output: 2022-09-30 21:39:25.220180

    The regex explained:

    1. ^.*?.d{0,6} // select from the begin everything including the dot
                     // and max 6 digits
    2. K            // forget the previous match and start again from the 
                     // point where 1. ended
    3. d*           // select all digits left
    4. replace the match with "" 
    
    Login or Signup to reply.
  2. With ‘?’ in the format, all digits after the 6th digit can be cut off.

    $string = '2022-09-30T21:39:25.220185123Z';
    $date   = date_create_from_format( "Y-m-dTH:i:s.u???P" , $string);
    var_dump($date);
    

    https://3v4l.org/Upm6v

    As of PHP version 8.0.10, strings like ‘2022-09-30T21:39:25.220185674Z’ are recognized by DateTime without any problems.

    $str = '2022-09-30T21:39:25.220185674Z';
    $d = new DateTime($str);
    var_dump($d);
    /*
    object(DateTime)#1 (3) {
      ["date"]=>
      string(26) "2022-09-30 21:39:25.220185"
      ["timezone_type"]=>
      int(2)
      ["timezone"]=>
      string(1) "Z"
    }
    */
    

    https://3v4l.org/pI4kO

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search