我想将日期时间从UTC时区转换为UTC + 01之类的任何时区,也希望将时区名称(例如Asia / Calcutta)转换为UTC。
我怎样才能做到这一点?
这是我的代码
<?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
您必须使用有效的时区。除了使用UTC+1
(无效)之外,您还可以使用CET
(欧洲中部时间)或Europe/Berlin
(两者均取决于夏季/冬季时间),对于加尔各答,有些国家的时区在全年(UTC + 1:00)内有效, 您可以使用Asia/Calcutta
例子:
$date->setTimezone( new DateTimeZone( 'Asia/Calcutta' ) );
$date->setTimezone( new DateTimeZone( 'CET' ) );
$date->setTimezone( new DateTimeZone( 'Europe/Berlin' ) );
在docs上,您可以找到具有有效DateTimeZone值的列表。
更新:就像@Marc B的评论中提到的那样。和@deceze您可以使用
$date = new DateTime();
而不是使用
$date = new DateTime(date("Y-m-d H:i:s"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句