Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Date and time calculations in PHP

Sunday, November 30th, 2014 by Servage

TimeCalculations with date and time are essential to most web applications. It is both the ability to create and display a proper date, as well as being able to add or subtract intervals of time from it. For example being able to show the time an hour from now, or showing the date in 7 days. These are basic operations supported by PHP via the DateTime class. It offers an interface to create, manipulate and display DateTime objects in whatever scenario you might have.

There are many different ways of handling dates and times in PHP. Previously it was often recommended to work with Unix timestamps and add/subtract seconds from such timestamps, to perform calculations. However, nowadays PHP knows how to handle dates and times much more flexible,  at which we will have a look here.

PHP DateTime class

You can create a new DateTime instance like below:

$date = new DateTime('2014-01-01');

This builds a new object with the set data of January 1st 2014. The first argument to the constructor passing the date for the new instance can be any string value understood by strtotime() as well. Exact examples are described in the PHP documentation.

You can also set the DateTime object from a Unix Timestamp like below:

$date = new DateTime();
$date->setTimestamp(1171502725);

If you need to switch the date or time part, you can do so selectively like below:

$date = new DateTime();
$date->setDate(2001, 2, 3);
$date->setTime(14, 55, 24);

Modify a DateTime using relative values

Beyond setting the date and time like described above, you can also perform relative calculations with the time, such as adding or subtracting a time interval. This is very useful when working based on current time, knowing which intervals to add. You can for example switch the date to tomorrow or the time to previous hour.

Add time intervals using the DateTime’s “modify” method like below:

$date->modify('+3 hour');
$date->modify('+2 day');
$date->modify('+1 year');

Subtracting intervals is equally easy:

$date->modify('-3 hour');
$date->modify('-2 day');
$date->modify('-1 year');

Modify a DateTime using a DateInterval

The examples above provide a string-based modification of the DateTime object. You can also use the DateTime’s “add” method to work with PHP’s DateInterval objects instead. This provides an object-oriented way of working with intervals, which may suit your needs better in some cases.

// Create an object for the date of January 1st 2014
$date = new DateTime('2014-01-01');

// Create an object for an interval of 1 year
$interval = new DateInterval('P1Y');

// Add the intervall to the date
$date->add( $interval );

Notice how the interval constructor takes a string to define a period. The string always start with “P”, followed by the “amount” or “intervals”, like “P1Y” for “Period 1 Year” in the example above. The following period indicators are available:

  • P = Period (before date based intervals)
  • Y = Year
  • M = Month
  • W = Week
  • D = Day
  • T = Time (before time based intervals)
  • H = Hour
  • M = Minute
  • S = Second

The intervals can be combined. For example a “Period of 1 Day and 2 Hours” would be “P1DT2H”.

Display a formatted DateTime value

The DateTime object contains the date and time in its properties. You can get and display a formatted version of the DateTime object using its “format” method. The method takes a string representation of the intended format just like the date() function:

$date = new DateTime('2014-01-01');
echo $date->format('Y-m-d H:i:s');

The example displays midnight on January 1st 2014 because that is the default time when no time was set in the DateTime creation.

References & more reading

PHP DateTime documentation

PHP DateInterval documentation

 

Date and time calculations in PHP, 4.0 out of 5 based on 4 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.