问题
I have done a little experiment on php's DateTime class. In the documentation they have suggested the syntax for creating the object of DateTime class as given.
Object oriented style:
public DateTime::__construct() ( [ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
Procedural style:
DateTime date_create ( [ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
Returns new DateTime object.
Here the first argument they have specified as mandatory, as a date/time string as specified in Date and Time Formats section. Or we have to pass NULL here to obtain the current time when using the $timezone parameter.
But my problem is when I am giving following code:
date_default_timezone_set('America/Los_Angeles');
$d_ob = new DateTime('x');
echo $d_ob->format('Y-m-d');
It's supposed to generate exception, but it's echoing the current date time like -
2013-09-29
I am not getting the point, how it's working?
回答1:
Apparently, this is not a bug, it is 'expected, but undocumented behaviour'See the comments to the bug report. All single letters (except for 'j') represent military timezones, see some code to demonstrate this.
There is more information here.
From RFC822
The military standard uses a single character for each zone. "Z" is Universal Time. "A" indicates one hour earlier, and "M" indicates 12 hours earlier; "N" is one hour later, and "Y" is 12 hours later. The letter "J" is not used.
So to answer your question
I am not getting the point, how it's working?
When DateTime::__construct() is passed a single value that is not a valid time string it assumes that the first parameter has been omitted and tries to parse the string as a time zone. As the RFC explains, 'x' is a valid timezone, so you will get a DateTime instance that is in timezone 'X'.
I should mention that although the constructor of \DateTime recognises these single letter zones, the constructor of \DateTimeZone does not!
I hope that helps.
来源:https://stackoverflow.com/questions/19076825/datetime-constructor-in-php