将用户指定的日期和时间(使用mktime转换)调整为特定时区


Adjust user specified date & time (converted using mktime) to specific timezone

我已经为此挠头几个小时了,并决定寻求一些帮助。

我正在使用javascript日历来允许用户选择日期和时间。现在我希望这个时间相对于他们的时区(我已经记录在数据库中)。但是,我无法弄清楚如何存储输入。我知道我需要将 mktime 吐出的 UTC 时间戳调整为用户的时区,但我遇到了麻烦。

这是我尝试过的:

$time = $_POST['datetime']; // Dont worry I will sanitize the input
echo $time.'<br>';
$timezone = "Canada/Pacific"; // Just an example, this will be taken from the database
$timestamp = mktime($hours, $minute, 0, $month, $day, $year); // Based on $time, I just ignored my steps to get the hours etc here
date_default_timezone_set($timezone);
echo 'Your timezone: '.date("F j Y h:i:s A", $timestamp).'<br />';
date_default_timezone_set('UTC');
echo 'UTC: '.date("F j Y h:i:s A", $timestamp);

当我执行上述操作时,我得到的输出是:

30 October 2013 - 01:00 AM
Your timezone: October 29 2013 11:00:00 PM
UTC: October, 30 2013 06:00:00 AM

问题是,尽管用户输入 1:00 AM,但我预计 mktime 会将其转换为 1:00 的 UTC 时间戳,但是它似乎被转换为 UTC 时间戳,实际上是 6:00 AM。我无法弄清楚 5 小时的差异来自哪里,我不想在那里编码静态的 5 小时差异。

不过,在

修复之后,我想将时间戳保存为已调整的 UTC 时间戳,以便将来获取时间戳并执行以下操作:

$timezone = "Canada/Pacific";
date_default_timezone_set($timezone);
echo 'Time: '.date("F j Y h:i:s A", $timestamp); // $timestamp from the database

它应该输出:

30 October 2013 - 01:00 AM

任何帮助不胜感激!

使用DateTimeDateTimezone,你的生活会更轻松。

如果发布的日期时间采用 UTC,

则可以简单地在 UTC 时区中创建日期时间对象,如下所示:

$dt = new DateTime($_POST['datetime'], new DateTimezone('UTC'));
echo $dt->format('F j Y h:i:s A P');

如果要将时区更改为用户,可以在 DateTime 对象上调用setTimezone()

$dt->setTimezone(new DateTimezone('Canada/Pacific'));
echo $dt->format('F j Y h:i:s A P');

尝试演示


如果您发布的日期时间类似于 30 October 2013 - 01:00 AM ,那么您不能使用 new DateTime()strtotime(),因为它不是标准的日期时间格式。在这种情况下,您可以使用如下DateTime::createFromFormat

$dt = DateTime::createFromFormat('j F Y - h:i A', $_POST['datetime'], new DateTimezone('UTC'));

尝试演示