I just recently started using the DateTime object in PHP, and now I can't get this figured out.
I thought that DateTime
would take into account the default timezone I set with date_default_timezone_set
, but apparently it does not:
date_default_timezone_set('Europe/Oslo');
$str = strtotime('2015-04-12');
$date = new DateTime("@".$str);
$response['TZ'] = $date->getTimezone()->getName();
$response['OTZ'] = date_default_timezone_get();
$response['Date'] = $date->format('Y-m-d');
echo json_encode($response);
This is the response I get:
{
"TZ":"+00:00",
"OTZ":"Europe\/Oslo",
"Date":"2015-04-11"
}
Passing the correct DateTimeZone to the constructor is not working either, as DateTime ignores it when it is given an UNIX timestamp. (It works if I am passing a regular date string to the constructor).
If I do this the date comes up correctly:
$date->setTimezone(new DateTimeZone("Europe/Oslo"));
I don't really want to have to pass the timezone along every time I am dealing with a date, but from what it looks like I might have to?
I think it is because of what is written here: http://php.net/manual/en/datetime.construct.php
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).
You use a UNIX time stamp to setup the date for the DateTime object in the constructor.
Try to set the DateTime object using this way
$date = new DateTime('2000-01-01');
Hi you can always use inheritance just to bypass the problem. It's more explicit way
**
class myDate extends DateTime{
public function __construct($time){
parent::__construct($time);
$this->setTimezone(new DateTimeZone("Europe/Oslo"));
}
}
$str = strtotime('2015-04-12');
$md = new myDate("@".$str);
echo $md->getTimezone()->getName();
**
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With