DateTime constructor in php

妖精的绣舞 提交于 2020-01-01 05:29:04

问题


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

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