Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228
Did you know? The PHP dateTime object.

Comments Blog About Development Research Sites

Did you know? The PHP dateTime object.

Dec 8, 2007
As most of you know by now do I have a fulltime job as a PHP programmer. This means exploring a language to its fullest depths, and sometimes coming across interesting points in it, so I figured I might as well write about that ;)

Our item for today: the new dateTime object:

Code (php) (nieuw venster):
1
2
3
4
5
6
7
8
$currentDate = new DateTime('2008-01-04');
$endDate     = new DateTime('2009-01-04');

while(
$currentDate < $endDate) {
  echo
$currentDate -> format('Y-m-d') . ' t/m ';  
  $currentDate      -> modify('+1 week');
  echo
$currentDate -> format('Y-m-d') . ' ';
}
This little gem was introduced in PHP 5.1 and deemed stable in 5.2 although I still can't find any documentation on it. When using it in compares it probably evaluates as a timestamp integer seeing how the above example works, but I'm not very sure about it. What I am sure about is that it has a modify member which, happily, takes a string as argument in a normally readable format. Not only '+1 week' works, but just about anything you can come up with!

A pitfall is the fact that it can't seem to handle timestamps as input - they're evaluated as strings. A workaround for this is also available:
Code (php) (nieuw venster):
1
$dateTime = new DateTime('@'. time() );
I wonder why they do not simply check the type of the argument and if it's an integer interpret it as a timestamp, but thats Zend for ya - they don't even want to fix it!

FragFrog out!

Jan 7, 2008 Harro

The best bit about it is that it doesn't store it's dates in an int.. (Millenium bug 38 years later anyone? http://en.wikipedia.org/wiki/Year_2038_problem)

Jan 7, 2008 Matthijs

Are you sure? Does look that way to me? Can't seem to find any documentation on it either?

Jan 25, 2008 Matthijs

According to this link the datetime object uses a 64 bit integer internally. This means that, as opposed to Date(), the DateTime object is actually not vulnerable to that bug!

In addition, it can also finally handle pre-1970 dates! :)

Aug 27, 2008 volo

i was apalled when i discovered that calculating a date in the near future caused so much trouble. My car licence expires way after the timestamp integers does. Thank god they created this. It's still new though, and there's code like $currentDate -> add() & etc, which still is only in experimental phases. No documentation either.

New comment

Your name:
Comment: