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
2
3
4
5
6
$datetime1 = new DateTime();
$datetime2 = new DateTime('2013-01-03 17:13:00');
$interval  = $datetime1->diff($datetime2);
$elapsed   = $interval->format('%y years, %m months, %d days, 
                                %h hours, %i minutes, %S seconds');
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
2
3
4
5
6
7
8
9
$elapsed = $interval->format('%y years, %m months, %d days, 
                              %h hours, %i minutes');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,', 
                            ' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ', 
                             ' 1 hours, ', ' 1 minutes'), array('1 year, ', 
                             '1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'), 
                       $elapsed);
echo $elapsed;

See it in action

Birthdays/calculate age

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

See it in action

Adding period of time to a date

For PHP 5.3 or newer

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

See it in action

For PHP 5.2

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

See it in action

Start date for a given week

1
2
3
4
$start_date  = new DateTime("2013-05-13");
$day_of_week = $start_date->format("w");
$start_date->modify('-' . $day_of_week . ' day');
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
2
3
4
5
6
7
8
9
$start    = new DateTime('2013-02-01');
$end      = new DateTime('2013-02-17');
$interval = new DateInterval('P1D');
$period   = new DatePeriod($start, $interval, $end);
 
foreach ($period as $dt)
{
    echo $dt->format("l Y-m-d") . PHP_EOL;
}

See it in action

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

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

See it in action

For PHP 5.2

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

See it in action

List all days in a month

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

See it in action

For PHP 5.2

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

See it in action

Get first day of the month

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

See it in action

Get last day of the month

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

See it in action

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

See it in action

Getting tomorrows date

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

See it in action

Or alternatively

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

See it in action

For PHP 5.2

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

See it in action

Compare dates & times

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

See it in action

Related Posts:

2 thoughts on “Working With Dates and Times in PHP

  1. We have the same surname, i’m Nicolas Conde haha! i wish i had your programming skills too … T_T

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>