Date function in PHP gives always date one day behind

有些话、适合烂在心里 提交于 2020-01-16 00:50:30

问题


My situation is that get always the dates one day behind. For example, I have this value -243219600 which is relative to date 18/04/1962

After a

date('d/m/Y', -243219600);

Output is :

17/04/1962

-243219600 seconds from January 1 1970 00:00:00 UTC in javascript is here you get correct Date.


回答1:


The output of date() depends on the configured time zone. If you add the time and timezone, you can see it. In my case it is CET:

echo date('d/m/Y H:m:i T', -243219600);
//prints: 18/04/1962 00:04:00 CET

Solution with date()

If you want date() to use UTC, use date_default_timezone_set:

date_default_timezone_set('UTC');
echo date('d/m/Y H:m:i T', -243219600);"

Output

 17/04/1962 23:04:00 UTC

(you see, since it is one hour before midnight in UTC, the date depends on the timezone)

Solution with DateTime:

The DateTime class uses always UTC if it is constructed by a Unix timestamp:

From the documentation:

Note:

The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

So you can use the following code as well:

echo (new DateTime('@-243219600'))->format('d/m/Y');



回答2:


Check the timezone of your PHP, set it so it's the same as your computer (since your using javascript).



来源:https://stackoverflow.com/questions/32500442/date-function-in-php-gives-always-date-one-day-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!