Elliott Brueggeman - PHP and Web Development Info, Photography, and More
 
Home | Web Dev Blog & Articles | PHPGraphLib | PHPSimpleChat | SkinnyTip | PHPWeatherLib | Photography | Contact
Posted on November 5, 2007 in PHP by Elliott BrueggemanNo Comments »

If you’re a seasoned PHP developer, and you initially learned PHP a few years ago, you may not be familiar with the new functions that PHP 5 (5.1+) provides for date manipulation. PHP has changed to an object based format, where you create an initial date object, modify if desired, and then output using a format you specify. This is a great step for PHP, which prior to these new functions, had many separate yet similar functions to do the same things.

Example code:

date_default_timezone_set ("America/New_York");
$date_object=date_create("9/18/2007");
$date_object->modify("+5 day");
echo $date_object->format("Y-m-d");

This will print 2007-09-23.

Note that we call the date_default_timezone_set() function before executing any date related code. This is a good idea when you are using a hosted site, where you do not have access to the php.ini file to set the master PHP timezone setting. List of available timezones.

The date_create() function takes any descriptive time string, identical to the older strtotime() function. See the manual page for date_create, strtotime and GNU Date Input Formats for more information on how to specify a date related string for the date_create() function.

The date_format() function takes a format argument identical to the syntax that the date() function accepts. See the date_format and date PHP manual pages for more information.