Paulund

Learn How To Use DateTime With PHP

In version 5.2 of PHP the DateTime class was introduced, in this tutorial we are going to investigate how the DateTime class can be used and why it's better to use this class over the old date() and time() functions. The date() function can be used to output a string that represents the date/time provided, it takes two parameters the first parameter defines what format the string is returned, the second parameter defines what time to return. If no second parameter is set it will use the current time, or you can provide a unix timestamp to return a different date.


// Current time
echo date("Y-m-d", time());

// 2013-12-01
echo date("Y-m-d", 1385925192);

The time() function will return a unix timestamp of the current time.


// Current time, unix timestamp
echo time();

Datetime()

The DateTime object was introduced in version 5.2 and comes with a number of other objects to help handle the problems you would face when using the date() and time() functions. We also get objects for DateTimeZone to handle the timezone location of the time you want, the DateInterval object which represents a interval such as 2 days from a certain date, DatePeriod object presents the period between two dates. The main difference between using the date() function and the DateTime object is that it's easier to modify the date values, if you want to display a date and time using the date() function it's quite easy you just do the following.


echo date("l jS \of F Y h:i:s A");

If you want to set this to a certain timezone you can do so by using the function date_default_timezone_set. date_default_timezone_set('UTC');


echo date("l jS \of F Y h:i:s A");

The problem will come when you need to modify or compare dates, using the DateTime object you can use the modify() or diff() methods to get the values. This is where the DateTime object can help when you have to do any manipulating of the date. To use the DateTime object you just need to instantiate the the class.


$date = new DateTime();

The constructor of this object takes two parameters the first is the time value you want to set the value of the object, you can use a date format, unix timestamp, a day interval or a day period. The second parameter is the timezone that you want to assign the date value.


// Set the date
$date = new DateTime('2000-01-01');

// Set the date at a specific timezone
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));

// Set date for 4 days from now
$date = new DateTime('+4 days');

Output Date In Format

The DateTime object has a date value, you can output this value by using the format() method and assigning what format to return in.


echo $date->format('Y-m-d');

Output Timestamp

If you want to output the DateTime value as a timestamp you will use the method getTimestamp().


$date = new DateTime();

echo $date->getTimestamp();

Setting Date

Although you will set the date used on the constructor of the DateTime object you can also use additional methods to set the date and time after the constructor.

Changing The Date

To change the date on the object you will use the setDate() method.


$date = new DateTime();

// Outputs 2001-02-03 $date->setDate(2001, 2, 3);


echo $date->format('Y-m-d');

Changing The Time

To change the time of the DateTime object you will use the method setTime();


$date = new DateTime();

// Output 2013-12-01 14:55:00 $date->setTime(14, 55); echo $date->format('Y-m-d H:i:s');

Changing The Timestamp

If you want to change the date time by using a timestamp you can use the method setTimestamp().


$date = new DateTime();

// Output 2013-11-28 19:13:19 $date->setTimestamp(1385665999); echo $date->format('Y-m-d H:i:s');

Setting Timezone

The second parameter into the DateTime Object is the DateTimeZone object, this allows you to assign a timezone to your DateTime object. Setting the timezone means that you can easily compare this value with another time to work out the total time difference between the two timezones.


// Outputs 2013-12-01 13:45:00+13:45
$date = new DateTime('2013-12-01', new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP');

You can also set the timezone with the method setTimezone().


$date = new DateTime('2013-12-01');

// Outputs 2013-12-01 13:45:00+13:45
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP');

// Outputs 2013-11-30 19:00:00-05:00
$date->setTimezone(new DateTimeZone('America/Toronto'));
echo $date->format('Y-m-d H:i:sP');

To get a full list of timezones you can see them at php.net List Of Timezones.

Add Days To Your Value

If you want to change the Date value in the DateTime object you can use the modify method to change the date value. Using this method you can pass in a string of days, months, years you want to change the value. For example if you want to add a number of days you can pass in +3 day, +1 month, +1 year. $date = new DateTime('2013-12-01'); $date->modify('+3 day'); // Outputs 2013-12-04


echo $date->format('Y-m-d');

$date = new DateTime('2013-12-01'); $date->modify('+1 month'); // Outputs 2014-01-01


echo $date->format('Y-m-d');

Compare Two Dates


$date1 = new DateTime('May 13th, 1986');
$date2 = new DateTime('October 28th, 1989');

$difference = $date1->diff($date2);

This will output the difference in the two dates and show you how many years, months and days, return in a DateInterval object.


DateInterval Object
(
    [y] => 3
    [m] => 5
    [d] => 15
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 1264
)

Convert Month Number To Month Name

A common task when working with dates is to get the month name when you have the month number, to return the month name all you have to do is output the month name by using the format F. By using the old date() function we can do this by passing in a unix timestamp as the second parameter and using F as the first parameter.


$monthName = date("F", mktime(0, 0, 0, $monthNum));

To use the DateTime class you can do this by using the format() method.


$date = new DateTime('2000-'.$monthNum.'-01');
$monthName = $date->format("F");

Get Number Of Weeks In A Month

The following code snippet will allow you to pass in a month and a year to return the amount of weeks that there are in a certain month.


<?php

function weeks_in_month($month, $year)
{
    $startDate = new DateTime();
    $startDate->setDate($year, $month, 1);

    $loopDate = $startDate;
    $week = 1;
    for($i = $startDate->format('d'); $i <= cal_days_in_month(CAL_GREGORIAN, $month, $year); $i++)
    {
        if($loopDate->format('w') % 7 == 0)
        {
            $week++;
        }

        $loopDate->modify('+1 day');
    }

    return $week;
}

echo '<p>Jan '.weeks_in_month(1, 2014).'</p>';
echo '<p>Feb '.weeks_in_month(2, 2014).'</p>';
echo '<p>Mar '.weeks_in_month(3, 2014).'</p>';
echo '<p>Apr '.weeks_in_month(4, 2014).'</p>';
echo '<p>May '.weeks_in_month(5, 2014).'</p>';
echo '<p>Jun '.weeks_in_month(6, 2014).'</p>';
echo '<p>Jul '.weeks_in_month(7, 2014).'</p>';
echo '<p>Aug '.weeks_in_month(8, 2014).'</p>';
echo '<p>Sep '.weeks_in_month(9, 2014).'</p>';
echo '<p>Oct '.weeks_in_month(10, 2014).'</p>';
echo '<p>Nov '.weeks_in_month(11, 2014).'</p>';
echo '<p>Dec '.weeks_in_month(12, 2014).'</p>';
?>

Get Last Day Of Month

Using the modify function it allows you to easily get the last day of the month by simply by writing the words in plain English. $date = new DateTime('now'); $date->modify('last day of this month');


echo $date->format('Y-m-d');