[英]Correctly converting to timezone from UTC in MySQL database with PHP
I see that a stored date value in phpmyadmin is 2020-03-03.我看到 phpmyadmin 中存储的日期值为 2020-03-03。 In PHP, I set the default timezone to UTC and the user's timezone to America/New_York:
在 PHP 中,我将默认时区设置为 UTC,将用户的时区设置为 America/New_York:
date_default_timezone_set('UTC');
$userTimeZone = new DateTimeZone('America/New_York');
I retrieve my date from the database, set the timezone on the date, and make it into a string.我从数据库中检索我的日期,在日期上设置时区,并将其转换为字符串。 It now equals a day earlier.
现在等于一天前。 (03-02-2020)
(03-02-2020)
$dateNeeded = new DateTime($row['dateNeeded']);
$dateNeeded->setTimeZone($userTimeZone);
$dateNeededStr = $dateNeeded->format('m-d-Y');
What did I do incorrectly here?我在这里做错了什么?
It is not incorrect.这是不正确的。 Your date is stored without the time component, which means when you put it in a
DateTime
constructor, it will be created as midnight ( $dateNeeded = new DateTime($row['dateNeeded'])
will have the value of 2020-03-03 00:00:00
.您的日期存储时没有时间组件,这意味着当您将其放入
DateTime
构造函数时,它将被创建为午夜( $dateNeeded = new DateTime($row['dateNeeded'])
将具有2020-03-03 00:00:00
。
That's in UTC timezone because you defined it so at the start.这是在 UTC 时区,因为您在开始时就定义了它。 So when you change the timezone, it will move back (as New York is UTC - 5) and gain the value of
2020-03-02 19:00:00
.因此,当您更改时区时,它将返回(因为纽约是 UTC - 5)并获得
2020-03-02 19:00:00
的值。
Since you're only outputting the date in your format (and not the time), it comes out as a day early.由于您仅以您的格式输出日期(而不是时间),因此它会提前一天输出。
Dont use date_default_timezone_set('UTC');
不要使用
date_default_timezone_set('UTC');
because MySQL server will use server timezone not UTC,因为 MySQL 服务器将使用服务器时区而不是 UTC,
In example,例如,
Your server time zone is GMT +2您的服务器时区是 GMT +2
And you set your server timezone to GMT +0;并且您将服务器时区设置为 GMT +0;
Then you read your date on database which stored on GMT + 2 time zone然后您在存储在 GMT + 2 时区的数据库上读取您的日期
When you try to convert it to other timezone, eg GMT + 5,当您尝试将其转换为其他时区时,例如 GMT + 5,
It will shift 7 hour not 5 hour它将移动 7 小时而不是 5 小时
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.