简体   繁体   中英

php timezone: DateTime::createFromFormat ignores timezone

I'm using php 5.6.17 on debian 8. After set up owncloud, I noticed, that the logs which are self written by owncloud (not by apache) has wrong time zones.

I investigated this a bit, seems like, that the line:

DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", ""), 'Europe/Berlin');

This does not care about any timezone setting. Instead of the time for Europe/Berlin (+1/+2) I get always the time for UTC.

In /etc/php5/apache2/php.ini I set "date.timezone = "Europe/Berlin" and the system time (debian) is also correct.

Even If I run somthing like below I get the same output (UTC):

 $time=DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), new DateTimeZone('UTC'));
 echo $time->format('c') . "\n";
 $time=DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), new DateTimeZone('Europe/Berlin'));
 echo $time->format('c') . "\n";

Any ideas about this problem?

Quoting the PHP manual on DateTime::createFromFormat() :

Note: The timezone parameter and the current timezone are ignored when the time parameter either contains a UNIX timestamp (eg 946684800) or specifies a timezone (eg 2010-01-28T15:00:00+02:00).

If you want to change the timezone, you have to use the setTimezone() method after the object is created.

Timezone is ignored when creating with microtime because in the vast majority of cases unix timestamps and microtime are stored as UTC. Use setTimezone after createFromFormat to update the timezone:

$micro = microtime(true);
$dt = DateTime::createFromFormat('U.u', $micro);
$dt->setTimezone(new DateTimeZone('America/Los_Angeles'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM