DateTime constructor in php

I did a little experiment on php DateTime class. In the documentation, they suggested syntax for creating an object of the DateTime class, as indicated.

Object Oriented Style:

public DateTime::__construct() ( [ string $time = "now" [, DateTimeZone $timezone = NULL ]] ) 

Procedural style:

 DateTime date_create ( [ string $time = "now" [, DateTimeZone $timezone = NULL ]] ) 

Returns a new DateTime object.

Here is the first argument that they indicated as required, as the date / time string specified in the Date and Time Format section. Or we must pass NULL here to get the current time when using the $ timezone parameter.

But my problem is that I give the following code:

 date_default_timezone_set('America/Los_Angeles'); $d_ob = new DateTime('x'); echo $d_ob->format('Ym-d'); 

It should throw an exception, but it repeats the current time of the date, for example -

 2013-09-29 

I donโ€™t understand how it works?

+6
source share
1 answer

Apparently this is not a bug, it is an โ€œexpected but undocumented behaviorโ€ See comments on the bug report . All single letters (with the exception of โ€œjโ€) represent military time intervals, see Code Demonstrating This .

More information here .

From RFC822

The military standard uses one character for each zone. "Z" is universal time. โ€œAโ€ indicates an hour earlier, and โ€œMโ€ indicates 12 hours earlier; "N" - after an hour, and "Y" - after 12 hours. The letter "J" is not used.

So, to answer your question

I donโ€™t understand how it works?

When DateTime :: __ construct () is passed a single value that is not a valid time string, it assumes that the first parameter is omitted and tries to parse the string as a time zone. As the RFC explains, โ€œxโ€ is a valid time zone, so you get an instance of DateTime that is in the time zone โ€œXโ€.

It should be noted that although the \ DateTime constructor recognizes these one-letter zones, the \ DateTimeZone constructor does not work!

I hope this helps.

+5
source

Source: https://habr.com/ru/post/954878/


All Articles