在 PHP 中将时间和日期从一个时区转换为另一个时区

2022-01-16 00:00:00 timezone php

基本上我需要的是一个脚本,当提供时间和时区时,它可以返回另一个时区的时间.

Basically what I need is an script that, when provided with a time and a timezone can return the time in another time zone.

我的主要问题是:

  • 从何处获取与 GMT 的时间偏移 - 是否有可用的公共数据库?
  • 如何同时考虑夏令时 (DST) 差异.
  • 如何将其全部封装在 PHP 类中 - 或者是否已经有这样的类可用?

推荐答案

<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "
";

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "
";
?>

上面的例子会输出:

2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45

可在 php.net 上的日期时间手册

就像 Pekka 说的:DateTime 类从 5.2 开始存在,您首先必须找出哪些方法是真正实现的,哪些只从 5.3 开始存在.

Like Pekka said: The DateTime class exists from 5.2 on and there you first have to find out which of the methods are realy implemented and which one only exist from 5.3 on.

相关文章