phpdatetimephp-8.1intldateformatter

DateTime() and IntlDateFormatter diffrent hours when convert timezone


Example:

$date = new DateTime('2023-09-08 06:00:00.0', new DateTimeZone('UTC')); // USER's timezone

echo $date->format('Y-m-d H:i:s');

$formatter = new IntlDateFormatter(
    'en', 
    IntlDateFormatter::SHORT, 
    IntlDateFormatter::SHORT, 
    'CST', 
    IntlDateFormatter::GREGORIAN,
    'YYYY-MM-dd HH:mm'
);
echo '</br>';
echo $formatter->format($date );

echo '</br>';
$date->setTimezone(new DateTimeZone('CST'));
echo $date->format('Y-m-d H:i:s');

output:

2023-09-08 06:00:00

2023-09-08 01:00

2023-09-08 00:00:00

why results is diffrent, which one is correct?


Solution

  • In the pattern you've provided to IntlDateFormatter, you're using 'YYYY' which represents the "week year". You should use 'yyyy' for the calendar year.

    $date = new DateTime('2023-09-08 06:00:00.0', new DateTimeZone('UTC')); // USER's timezone
    
    echo $date->format('Y-m-d H:i:s');
    
    $formatter = new IntlDateFormatter(
        'en', 
        IntlDateFormatter::SHORT, 
        IntlDateFormatter::SHORT, 
        'America/Chicago', // Use a full time zone identifier
        IntlDateFormatter::GREGORIAN,
        'yyyy-MM-dd HH:mm' // Use 'yyyy' instead of 'YYYY'
    );
    echo '</br>';
    echo $formatter->format($date );
    
    echo '</br>';
    $date->setTimezone(new DateTimeZone('America/Chicago')); 
    echo $date->format('Y-m-d H:i:s');