如何在 PHP 中获取指定时区的当天午夜?

kfr*_*zen 5 php datetime

我在纽约有一台服务器,在加利福尼亚州有一个“客户端”,该服务器希望该服务器能够计算出加利福尼亚州当天的午夜,这与纽约一天中三个小时的午夜时间不同。

我只能计算纽约当天的午夜,但我需要能够计算加利福尼亚州(或任何其他任意时区)当天的午夜

我确实可以访问时区与 UTC 的偏移量。

$tzOffset = "-700"; // Timezone offset from UTC (in this case, PDT)
Run Code Online (Sandbox Code Playgroud)

我现在使用的(半工作)方法是

strtotime("00:00:00 " . $tzOffset);
Run Code Online (Sandbox Code Playgroud)

在太平洋夏令时间 6 月 25 日晚上 10:00,此方法将返回太平洋夏令时间 6 月 26 日上午 12:00 作为午夜,而它本应返回太平洋夏令时间 6 月 25 日上午 12:00。

sec*_*tus 5

// create time from string
$date_time = new Datetime('midnight', new Datetimezone('America/Los_Angeles'));
// string representation of time in America/Los_Angeles
echo $date_time->format('Y-m-d H:i:s') . PHP_EOL;
$date_time->setTimezone(new Datetimezone('America/New_York'));
// string representation of the same time in America/New_York
echo $date_time->format('Y-m-d H:i:s') . PHP_EOL;
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/datetime.formats.php