PHP DateTime操作 - 设置新时区并扣除24小时

时间:2017-03-16 03:42:40

标签: php date datetime

我在PHP中使用datetime()语句时非常困难。我想要实现的是读取当前服务器时间(位于GMT-5),根据时间计算用户特定日期和时间的时区,然后从用户当前时间扣除24小时。请参阅下面的示例,了解伦敦和上海的用户:

$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;

echo "<hr>";

$server_datetime = new \DateTime('now');  //located in America/New_York timezone - GMT-5
$server_newdate = (new \DateTime())->modify('-1 day');
echo "Current Server DateTime: " . $server_datetime->format('Y-m-d H:i:s') . "<br>";
echo "If you deduct 24 hours you get " . $server_newdate->format('Y-m-d H:i:s');

echo "<hr>";

$usersTimezone1 = 'Europe/London';  // GMT-0
$user_datetime1 = $server_datetime->setTimezone(new DateTimeZone($usersTimezone1));
$user_newdate1 = ($server_datetime->setTimezone(new DateTimeZone($usersTimezone1))->modify('-1 day'));
//$user_newdate1 = $user_datetime1->modify('-1 day');
echo "London User DateTime: " . $user_datetime1->format('Y-m-d H:i:s') . "<br>";
echo "If you deduct 24 hours you get " . $user_newdate1->format('Y-m-d H:i:s');

echo "<hr>";

$usersTimezone2 = 'Asia/Shanghai';  // GMT+8
$user_datetime2 = $server_datetime->setTimezone(new DateTimeZone($usersTimezone2));
$user_newdate2 = $user_datetime1->modify('-1 day');
echo "Shanghai User DateTime: " . $user_datetime2->format('Y-m-d H:i:s') . "<br>";
echo "If you deduct 24 hours you get " . $user_newdate2->format('Y-m-d H:i:s');

正如您所看到的,问题是我无法直接从$ user_datetime变量中扣除24小时,该变量保存用户时区的当前时间。既没有直接从变量中扣除也没有为这个时区创建一个新的datetime()实例似乎可以解决这个问题。

// attempt 1 - not working
    $user_datetime1 = $server_datetime->setTimezone(new DateTimeZone($usersTimezone1));
    $user_newdate1 = ($server_datetime->setTimezone(new DateTimeZone($usersTimezone1))->modify('-1 day'));

// attempt 2 - not working either
$user_datetime2 = $server_datetime->setTimezone(new DateTimeZone($usersTimezone2));
$user_newdate2 = $user_datetime1->modify('-1 day');

一旦我开始修改用户日期时间,脚本将只返回用户时区的当前日期和时间,没有别的。

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

作为一种最佳实践,您可以使用:

$serverDateTime = new DateTime();

$userTimezone = new DateTimeZone('Europe/London');

$userDateTime = $serverDateTime->setTimezone($userTimezone);

$dateInterval = new DateInterval('P1D');

echo $userDateTime->sub($dateInterval)->format('Y-m-d H:i:s');

但是如果你想直接从变量中减去,你可以使用这个:

$serverDateTime = new DateTime();

$userTimezone = new DateTimeZone('Europe/London');

$userDateTime = $serverDateTime->setTimezone($userTimezone)->sub(new DateInterval('P1D'))->format('Y-m-d H:i:s');

echo $userDateTime;

答案 1 :(得分:1)

//Asia/Kolkata +5:30
date_default_timezone_set("Asia/Kolkata");//set time zone
$istTime= strtotime(date("d-m-Y h:i:s"));//get timestamp in seconds
echo date("d-m-Y h:i:s");//16-03-2017 09:44:52

//Europe/London +0:00
date_default_timezone_set("Europe/London");//set new time zone
$dayBeforeTime= strtotime(date("d-m-Y h:i:s",$istTime))-86400;//get timestamp in seconds and subtracting 1 day seconds
echo date("d-m-Y h:i:s",$dayBeforeTime);//15-03-2017 04:14:52