如何在 PHP 中将日期时间从 UTC 转换为 UTC+01(也在 Asia/Calcutta 中)

how to convert date time from UTC to UTC+01 (also in Asia/Calcutta) in PHP

我想将日期时间从时区 UTC 转换为任何时区,例如 UTC+01 以及时区名称,例如Asia/Calcutta.

我该怎么做?

这是我的代码

<?php
date_default_timezone_set("UTC");
$date = new DateTime(date("Y-m-d H:i:s"));
$date->setTimezone(new DateTimeZone('UTC+01')); 
echo $date->format('Y-m-d H:i:s'); 
?>

我收到以下错误:

Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::__construct(): Unknown or bad timezone (UTC+01)' in /var/www/html/test/index.php:6 Stack trace: #0 /var/www/html/test/index.php(6): DateTimeZone->__construct('UTC+01') #1 {main} thrown in /var/www/html/test/index.php on line 6 

您必须使用有效的时区。您可以使用 CET(中欧时间)或 Europe/Berlin(两者都取决于 summer/wintertime),而不是使用 UTC+1(无效),也有一些国家/地区使用此时区全年有效(UTC+1:00),对于加尔各答,可以使用Asia/Calcutta

示例:

  • $date->setTimezone( new DateTimeZone( 'Asia/Calcutta' ) );
  • $date->setTimezone( new DateTimeZone( 'CET' ) );
  • $date->setTimezone( new DateTimeZone( 'Europe/Berlin' ) );

Here at the docs, you can find a list with valid DateTimeZone 个值。

更新: 就像 @Marc B 的评论中提到的那样。和 @deceze 你可以使用

$date = new DateTime();

而不是使用

$date = new DateTime(date("Y-m-d H:i:s"));