Search code examples
phpdatedatetimestrtotime

How to convert string into timezone aware date


Hello I have a string 2020-08-19 13:04:53. I know that this time is in Sydney, Australia time. However, I need to convert this time into New York, America time as a date object. How can I do this?

date_default_timezone_set("Australia/Sydney");
$time = '2020-08-19 13:04:53';
$date = date('Y-m-d H:i:s', $time);

Solution

  • I would try something like

    <?php
    $date = new DateTime('2020-08-19 13:04:53', new DateTimeZone('Australia/Sydney'));
    echo $date->format('Y-m-d H:i:s');
    // Output: 2020-08-19 13:04:53
    
    $date->setTimezone(new DateTimeZone('America/New_York'));
    echo $date->format('Y-m-d H:i:s');
    // Output: 2020-08-18 23:04:53