Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime constructor in php

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?

like image 672
ritesh Avatar asked Sep 29 '13 10:09

ritesh


People also ask

What is DateTime in PHP?

The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format. Syntax: Object oriented style string DateTime::format( string $format )

How do we use DateTime objects in PHP?

To use the DateTime object you just need to instantiate the the class. $date = new DateTime(); The constructor of this object takes two parameters the first is the time value you want to set the value of the object, you can use a date format, unix timestamp, a day interval or a day period.

What is timestamp format in PHP?

What is a TimeStamp? A timestamp in PHP is a numeric value in seconds between the current time and value as at 1st January, 1970 00:00:00 Greenwich Mean Time (GMT).


1 Answers

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.

like image 105
vascowhite Avatar answered Oct 22 '22 21:10

vascowhite