我开发了一个应用程序,可以记录某些记录的修改和创建时间,所以基本上我们使用
time()
功能来记录更改何时保存。
我在英国,所以我的时区必须是 GMT。然而在英国,我们使用 DST,所以在夏天我们不再使用 GMT,而是使用 BST。
如何将时区更改为使用 BST(即 GMT +1)。我想在我的 php 文件中声明它,以便轻松更改。这是我现在所拥有的:
date_default_timezone_set("UTC");
当我将其更改为:
date_default_timezone_set("BST");
我收到 php 错误
Timezone ID 'BST' is invalid
,当我将其更改为欧洲/伦敦时,它仍然保持为 GMT 而不是 BST
您可以将时区设置为
Europe/London
,它会在适当的日期自动在 GMT 和 BST 之间转换。时区包含这些信息,这基本上就是时区的要点(在 PHP 意义上)。
PHP 手册轻松地包含了 作为示例:
$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions();
print_r(array_slice($transitions, 0, 3));
Array
(
[0] => Array
(
[ts] => -9223372036854775808
[time] => -292277022657-01-27T08:29:52+0000
[offset] => 3600
[isdst] => 1
[abbr] => BST
)
[1] => Array
(
[ts] => -1691964000
[time] => 1916-05-21T02:00:00+0000
[offset] => 3600
[isdst] => 1
[abbr] => BST
)
[2] => Array
(
[ts] => -1680472800
[time] => 1916-10-01T02:00:00+0000
[offset] => 0
[isdst] =>
[abbr] => GMT
)
)
time()
函数返回一个unix时间戳,该时间戳始终基于UTC(与GMT相同)。调整为 BST 或任何其他时区都是无效的。
还有其他函数可以处理本地时间,以及将 unix 时间戳转换为字符串以供显示。这就是您使用
Europe/London
时区的地方。
BST
无效,因为它可能代表“孟加拉国标准时间”或少数其他时区。一般来说,不要依赖时区缩写。
date_default_timezone_set("Europe/London");
echo date('Y-m-d H:i:s');
在 date_default_timezone_set() 中使用“欧洲/伦敦”而不是 BST/GMT/UTC,这可能是处理实例时间的正确方法。这样,时区时间在页面实例处于活动状态的整个过程中都会保留。
存在一个问题,
Europe/London
时区可能与英国现实世界的实际时间相差 +/- 1 小时。
$var = time();
看这个例子:
print date_default_timezone_get();
print "\n";
print date('r',1698136637);
默认情况下 PHP 使用 UTC 时间,所以这将是:
世界标准时间
2023 年 10 月 24 日星期二 08:37:17 +0000
通过第三方软件记录,这是设置日期的正确时间。
但是,使用
Europe/London
有一个问题:
date_default_timezone_set('Europe/London');
print date_default_timezone_get();
print "\n";
print date('r',1698136637);
这给出了:
欧洲/伦敦
2023 年 10 月 24 日星期二 09:37:17 +0100
这不是正确的时间,因为这张唱片是在英国伦敦录制的,时间是上午 8:37。
解决方案:使用 UTC 而不是
Europe/London
时区。
我用它作为我的文学时钟https://bigjobby.com/time/
<?php
// Set the default timezone to UK
date_default_timezone_set('Europe/London');
// Get the current date and time
$now = new DateTime();
echo $now->format('Y-m-d H:i:s') . "\n";
// If you want to display the timezone
echo $now->getTimezone()->getName();
?>