腾讯云 cos-php-sdk 引起的时区混乱

起因

用 Laravel 做的管理系统需要统一修改时区为 UTC, config 文件中修改后本以为就好了,但是在某些情况下时区还是中国时区。
通过问题排查,确定了是 cos-php-sdk 的默认配置搞的鬼

复现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
namespace Admin;
use Qcloud\Cos\Client;

require "./vendor/autoload.php";

date_default_timezone_set("America/Los_Angeles");
echo date("Y-m-d H:i:s e") . "\r\n";
$cosConfig = [
'region' => "chengdu-1",
'credentials' => [
'secretId' => 'aaaaaaaaaa',
'secretKey' => 'aaaaaaaaaa',
],
];

$client = new Client($cosConfig);
echo date("Y-m-d H:i:s e") . "\r\n";

输出结果如下:

1
2
2026-05-07 22:50:01 America/Los_Angeles
2026-05-08 13:50:01 PRC

cos-php-sdk 会默认修改 php 运行时时区为 PRC 官方文档中没有提及任何这方面的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// https://github.com/tencentyun/cos-php-sdk-v5/blob/master/src/Client.php
private $cosConfig = [
'scheme' => 'http',
'region' => null,
'credentials' => [
'appId' => null,
'secretId' => '',
'secretKey' => '',
'anonymous' => false,
'token' => null,
],
'timeout' => 3600,
'connect_timeout' => 3600,
'ip' => null,
'port' => null,
'endpoint' => null,
'domain' => null,
'proxy' => null,
'retry' => 6,
'userAgent' => 'cos-php-sdk-v5.' . Client::VERSION,
'pathStyle' => false,
'signHost' => true,
'allow_redirects' => false,
'allow_accelerate' => false,
'timezone' => 'PRC',
'locationWithScheme' => false,
'autoChange' => false,
'limit_flag' => false,
'isCheckRequestPath' => true,
];

// https://github.com/tencentyun/cos-php-sdk-v5/blob/master/src/Signature.php
public function __construct( $accessKey, $secretKey, $options, $token = null ) {
$this->accessKey = $accessKey;
$this->secretKey = $secretKey;
$this->options = $options;
$this->token = $token;
$this->signHeader = [
'cache-control',
'content-disposition',
'content-encoding',
'content-length',
'content-md5',
'content-type',
'expires',
'host',
'if-match',
'if-modified-since',
'if-none-match',
'if-unmodified-since',
'origin',
'range',
'transfer-encoding',
'pic-operations',
];
date_default_timezone_set($this->options['timezone']);
}

解决方案

在配置中显式指定时区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
namespace Admin;
use Qcloud\Cos\Client;

require "./vendor/autoload.php";

date_default_timezone_set("America/Los_Angeles");
echo date("Y-m-d H:i:s e") . "\r\n";

$phpDefaultTimeZone = date_default_timezone_get();
$cosConfig = [
'region' => "chengdu-1",
'credentials' => [
'secretId' => 'aaaaaaaaaa',
'secretKey' => 'aaaaaaaaaa',
],
'timezone' => $phpDefaultTimeZone,
];

$client = new Client($cosConfig);
echo date("Y-m-d H:i:s e") . "\r\n";

输出

1
2
2026-05-07 22:54:40 America/Los_Angeles
2026-05-07 22:54:40 America/Los_Angeles

腾讯云 cos-php-sdk 引起的时区混乱

https://www.ddnpc.com/2026/cos-php-sdk-change-timezone/

作者

nyuFeng

发布于

2026-05-08

更新于

2026-05-08

许可协议

评论