PHP: 将本地时间转换为 UTC

PHP: Convert Local Time to UTC

假设我得到一个像 08/22/2015 10:56 PM 这样的字符串,并且这个 date/time 字符串总是只指一个特定的时区。我需要能够将其转换为这种格式:'Ymd\THis\Z',这是 iCal 格式。

  1. 如何将该字符串转换为祖鲁时间并转换为 'Ymd\THis\Z'
  2. 然后我该如何添加,比如说,30 分钟 date/time?

我一直在尝试用 strtotime 和 DateTime 解决这个问题,但我担心我做错了。也许有更简单直接的解决方案?

您可以使用 DateTime,示例如下:

<?php

$datetime = '08/22/2015 10:56 PM';
$tz_from = 'America/New_York';
$tz_to = 'UTC';
$format = 'Ymd\THis\Z';

$dt = new DateTime($datetime, new DateTimeZone($tz_from));
$dt->setTimeZone(new DateTimeZone($tz_to));
echo $dt->format($format) . "\n";

$minutes = 30;
$dt->add(new DateInterval('PT' . $minutes . 'M'));
echo $dt->format($format) . "\n";

根据主题行;要将 本地时间转换为 UTC,您需要给定本地时间的时区名称,或者如果您有 timezone offset 格林威治标准时间;您可以尝试以下操作:

//assume time zone is +3 hours
$offset = 3 * 60 * 60;
$date = date('H:i:s', strtotime("10:56 PM")- $offset);
echo $date;

这将输出:19:56:00 这是 UTC 时间