The Drupal 7 Date module provides a helpful class -- DateObject -- and many helpful functions for the manipulation of date and time values in code and the storage of these values in your site's database. The class and functions are well-documented here on DrupalContrib.

Using the DateObject class delivers advantages to any coder who needs to handle dates and times (referred to for the rest of this article as 'times') with proper consideration for time zones or needs to perform time arithmetic, combine time values, format time values for display, and other tasks. The class extends the PHP DateTime class and so includes all of the native capabilities of PHP for time value handling.

Create a DateObject

The class constructor method, which is the method called when a new instance of the object is created, takes up to three arguments, all of which are optional -- a time string, a PHP DateTimeZone object, and a string containing a PHP date() type format string. The time string can contain one or more date parts (i.e., year, month, date, hour, minute, and second), but all parts of lesser granularity must be included. In other words, a month cannot be included without a year, and a second cannot be included without all other parts.

// Create an object with just a date and no time
$example_date = new DateObject('January 1, 2013');

// Here's an object with all the possible parts for January 1, 2013 at 1:00 PM
$example_date = new DateObject('January 1, 2013 13:00:00');