Search code examples
phpdatetimeyoutubeyoutube-apiyoutube-data-api

How to parse YouTube returned date to timestamp?


YouTube returns the Updated date and Submitted on date as follows: 2010-08-22T04:46:18.000Z

Is there a PHP function, or a date mask that parses this?


Solution

  • $dt = DateTime::createFromFormat("Y-m-d\TH:i:s.uP", "2010-08-22T04:46:18.000Z");
    var_dump($dt);
    // object(DateTime)#1 (3) {
    //   ["date"]=>
    //   string(26) "2010-08-22 04:46:18.000000"
    //   ["timezone_type"]=>
    //   int(2)
    //   ["timezone"]=>
    //   string(1) "Z"
    // }
    

    This uses the DateTime class. It is timezone and fractional seconds aware. To display the date use the format method:

    echo $dt->format("Y-m-d H:i:s e");
    // 2010-08-22 04:46:18 Z
    

    To convert the date to local timezone use the setTimezone method:

    $dt->setTimezone(new DateTimeZone(date_default_timezone_get()));
    echo $dt->format("Y-m-d H:i:s e");
    // 2010-08-21 21:46:18 America/Los_Angeles