User Contributed Notes 14 notes

DateTime does not support split seconds (microseconds or milliseconds etc.)I don't know why this isn't documented.The class constructor will accept them without complaint, but they are discarded.There does not appear to be a way to take a string like "2012-07-08 11:14:15.638276" and store it in an objective form in a complete way.

It isn't obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using "double" speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using 'single' speech marks around the format string, then you only need one backslash.

For instance, to create a string like "Y2014M01D29T1633", you *could* use string concatenation like so:

This method involves fewer function calls, so probably is slightly quicker; and also is immune to race conditions if you are not specifying the second argument. [It's possible that you could evaluate date("d") just *before* midnight and date("H") just *after* midnight. This will not give you the result you were expecting.]

If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:

$date = new DateTime("2010-07-05T06:00:00Z", new DateTimeZone("Europe/Amsterdam"));

will create a DateTime object set to "2010-07-05 06:00:00+0200" (+2 being the TZ offset for Europe/Amsterdam)

This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:

If you need DateTime::createFromFormat functionality in versions <5.3.0 releases you might use the following basic class which can also be combined with Tom's class. It should work for most basic formats, however you should improve this function if you need more complex formats.

<?phpclass DateClass extends DateTime{

public function getTimestamp(){ return $this->format ("U");}

/*** This function calculates the number of days between the first and the second date. Arguments must be subclasses of DateTime**/static function differenceInDays ($firstDate, $secondDate){$firstDateTimeStamp = $firstDate->format("U");$secondDateTimeStamp = $secondDate->format("U");$rv = round ((($firstDateTimeStamp - $secondDateTimeStamp))/86400); return $rv;}

/*** This function returns an object of DateClass from $time in format $format. See date() for possible values for $format**/static function createFromFormat ($format, $time){assert ($format!=""); if($time==""){ return new DateClass(); }