Php 从UTC转换到任意时区

Php 从UTC转换到任意时区,php,datetime,Php,Datetime,我的linux设备已设置为使用UTC。给定一个时区和一个日期,我想获取日期范围,以便查询数据库中任何给定日期创建的记录。例如,如果美国/丹佛时区现在是2018-03-24上午9点。我想以UTC获取此日期的开始和结束时间。如何获得该日期开始时的UTC等效值 <?php $date = new DateTime(date('Y-m-d H:i:s'), new DateTimeZone('America/Denver')); $date->setTimezone(new Date

我的linux设备已设置为使用UTC。给定一个时区和一个日期,我想获取日期范围,以便查询数据库中任何给定日期创建的记录。例如,如果美国/丹佛时区现在是2018-03-24上午9点。我想以UTC获取此日期的开始和结束时间。如何获得该日期开始时的UTC等效值

<?php
$date = new DateTime(date('Y-m-d H:i:s'), new     DateTimeZone('America/Denver'));
$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('Y-m-d 00:00:00');
?>


返回的2018-03-24 00:00:00不正确。有指针吗?

尝试使用此函数

 function UTCTimeToLocalTime($time, $tz = '', $FromDateFormat = 'Y-m-d H:i:s', $ToDateFormat = 'Y-m-d H:i:s')
{
    if ($tz == '')
        $tz = date_default_timezone_get();

    $utc_datetime = DateTime::createFromFormat($FromDateFormat, $time, new
        DateTimeZone('UTC'));
    $local_datetime = $utc_datetime;

    $local_datetime->setTimeZone(new DateTimeZone($tz));
    return $local_datetime->format($ToDateFormat);
}

echo UTCTimeToLocalTime('2015-07-01 13:30:00','America/Denver');



function LocalTimeToUTCTime($time, $tz = '', $FromDateFormat = 'Y-m-d H:i:s', $ToDateFormat = 'Y-m-d H:i:s')
{
    if ($tz == '')
        $tz = date_default_timezone_get();
    $utc_datetime = DateTime::createFromFormat($FromDateFormat, $time, new
        DateTimeZone($tz));
    $local_datetime = $utc_datetime;
    $local_datetime->setTimeZone(new DateTimeZone('UTC'));
    return $local_datetime->format($ToDateFormat);
}

您向
DateTime
构造函数提供了一个伪造的本地时间:

new DateTime(date('Y-m-d H:i:s'), newDateTimeZone('America/Denver'));
             ^^^^
你告诉PHP这是丹佛当地时间,但你真的不知道。由于字符串不包含时区信息,PHP将使用

只需放下
date()
。它毫无用处,只会让事情变得更难

<?php
$date = new DateTime('now', new DateTimeZone('America/Denver'));
echo $date->format('r'), PHP_EOL;
$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('r'), PHP_EOL;

日期\默认\时区\设置('UTC');在PHP脚本之上。你创造的所有日期都是UTC预期的结果是什么?可能是作品的复制品,就像一个符咒。非常感谢。不过,我认为函数名应该称为LocalTimeToUTC。如果我传递一个本地时间(2018-03-24 00:00:00),它将返回UTC时间,对吗?2018-03-23 18:00:00我需要获取任何给定日期的日期时间范围。如果今天是美国/丹佛时间2018-03-24,我需要返回UTC时间,以便查询数据库中的日期记录。在UTC中,这需要是2018-03-23 18:00:00到2018-03-24 17:59:59。我已经编辑了我的答案,并使用了本地到UTC功能。如果我在2018-03-24 00:00:00传递给您的新功能,它将返回2018-03-24 06:00:00。第一个功能实际上会返回正确的UTC时间2018-03-23 18:00:00
Sun, 25 Mar 2018 06:11:21 -0600
Sun, 25 Mar 2018 12:11:21 +0000