Working With Dates and Times in PHP

Working with Dates and Times prior to PHP 5.2 meant using date(), strtotime(), and other date related functions sometimes in convoluted ways to get to the date(s) you were looking for. Fortunately with PHP 5.2 the DateTime() class were introduced. (DateTimeZone() was introduced as well but is not covered here). It was further enhanced in PHP with additionally methods as well as the new DatePeriod() and DateInterval() classes.

Getting Started

Before we get started I will link to the relevant pages in the PHP manual for the classes that we will be using here. All of these require running PHP 5.2 or newer. Make sure you check your version of PHP before using any of this code.

Also, keep in mind that when using DateTime(), when passing a Unix Timestamp as a parameter requires prepending an @ to the timestamp for it be recognized as a timestamp.

  1. $datetime = new DateTime('@123457890');

Getting the difference between two dates

  1. $datetime1 = new DateTime();
  2. $datetime2 = new DateTime('2013-01-03 17:13:00');
  3. $interval  = $datetime1->diff($datetime2);
  4. $elapsed   = $interval->format('%y years, %m months, %d days, 
  5.                                 %h hours, %i minutes, %S seconds');
  6. echo $elapsed;

See it in action

If you want to eliminate any periods that have zero values you can use the snippet below to remove them.

  1. $elapsed = $interval->format('%y years, %m months, %d days, 
  2.                               %h hours, %i minutes');
  3. $elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,', 
  4.                             ' 0 hours,', ' 0 minutes,'), '', $elapsed);
  5. $elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ', 
  6.                              ' 1 hours, ', ' 1 minutes'), array('1 year, ', 
  7.                              '1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'), 
  8.                        $elapsed);
  9. echo $elapsed;

See it in action

Birthdays/calculate age

  1. $today     = new DateTime();
  2. $birthdate = new DateTime("1973-04-18");
  3. $interval  = $today->diff($birthdate);
  4. echo $interval->format('%y years');

See it in action

Adding period of time to a date

For PHP 5.3 or newer

  1. $datetime = new DateTime();
  2. $datetime->add(new DateInterval('P6M'));
  3. echo $datetime->format('Y-m-d');

See it in action

For PHP 5.2

  1. $datetime = new DateTime();
  2. $datetime->modify('+6 months');
  3. echo $datetime->format('Y-m-d');

See it in action

Start date for a given week

  1. $start_date  = new DateTime("2013-05-13");
  2. $day_of_week = $start_date->format("w");
  3. $start_date->modify('-' . $day_of_week . ' day');
  4. echo $start_date->format('l, F jS, Y');

See it in action

Looping through the days between two dates

For PHP 5.3 or newer

  1. $start    = new DateTime('2013-02-01');
  2. $end      = new DateTime('2013-02-17');
  3. $interval = new DateInterval('P1D');
  4. $period   = new DatePeriod($start, $interval, $end);
  5.  
  6. foreach ($period as $dt)
  7. {
  8.     echo $dt->format("l Y-m-d") . PHP_EOL;
  9. }

See it in action

An alternative way to do this using DateInterval::createFromDateString()

  1. $start    = new DateTime('2013-02-01');
  2. $end      = new DateTime('2013-02-17');
  3. $interval = DateInterval::createFromDateString('1 day');
  4. $period   = new DatePeriod($start, $interval, $end);
  5.  
  6. foreach ($period as $dt)
  7. {
  8.     echo $dt->format("l Y-m-d") . PHP_EOL;
  9. }

See it in action

For PHP 5.2

  1. $start = new DateTime('2013-02-01');
  2. $end   = new DateTime('2013-02-17');
  3. while ($start < = $end)
  4. {
  5.     echo $start->format("m/d/Y") . PHP_EOL;
  6.     $start->modify("+1 day");
  7. }

See it in action

List all days in a month

  1. $start    = new DateTime('first day of this month');
  2. $end      = new DateTime('first day of next month');
  3. $interval = DateInterval::createFromDateString('1 day');
  4. $period   = new DatePeriod($start, $interval, $end);
  5.  
  6. foreach ($period as $dt)
  7. {
  8.     echo $dt->format("l Y-m-d") . PHP_EOL;
  9. }

See it in action

For PHP 5.2

  1. $start = new DateTime('2013-01-31');
  2. $end   = new DateTime('2013-02-05');
  3. while($start < = $end)
  4. {
  5.     echo $start->format("m/d/Y"). PHP_EOL;
  6.     $start->modify("+1 day");
  7. }

See it in action

Get first day of the month

  1. $datetime = new DateTime('first day of this month');
  2. echo $datetime->format('jS, F Y');

See it in action

Get last day of the month

  1. $datetime = new DateTime();
  2. echo $datetime->format('Y-m-t');

See it in action

  1. $datetime = new DateTime('last day of this month');
  2. echo $datetime->format('F jS');

See it in action

Getting tomorrows date

  1. $datetime = new DateTime('tomorrow');
  2. echo $datetime->format('Y-m-d');

See it in action

Or alternatively

  1. $datetime = new DateTime();
  2. $datetime->add(new DateInterval("P1D"));
  3. echo $datetime->format('Y-m-d');

See it in action

For PHP 5.2

  1. $datetime = new DateTime();
  2. $datetime->modify('+1 day');
  3. echo $datetime->format('Y-m-d');

See it in action

Compare dates & times

  1. $date1 = DateTime::createFromFormat('H:i', '08:00');
  2. $date2 = new DateTime();
  3. if ($date1 > $date2)
  4. {
  5.     echo 'It is after 08:00';
  6. }
  7. else
  8. {
  9.     echo 'It is not after 08:00';
  10. }

See it in action

2 thoughts on “Working With Dates and Times in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *