Today, we’ll discuss how to calculate date and time difference in PHP.
In PHP, there are many ways to calculate date and time difference, in this tutorial we’ll discuss several ways to solve the task, from the simplest to the most complex.
I. How to Calculate Time Difference in PHP – Using date_diff Function – The Easiest Way
The easiest way to calculate the time difference in PHP is using date_diff
function(), this function available from PHP version 5.3.0. the format is:
date_diff($datetime1, $datetime2)
Some examples:
<?php
$start = date_create('1988-08-10');
$end = date_create(); // Current time and date
$diff = date_diff( $start, $end );
echo 'The difference is ';
echo $diff->y . ' years, ';
echo $diff->m . ' months, ';
echo $diff->d . ' days, ';
echo $diff->h . ' hours, ';
echo $diff->i . ' minutes, ';
echo $diff->s . ' seconds';
// Output: The difference is 28 years, 5 months, 19 days, 20 hours, 34 minutes, 36 seconds
echo 'The difference in days : ' . $diff->days;
// Output: The difference in days : 10398
Explanation:
- The arguments, which are
$datetime1
and $datetime2 must be an object ofDateInterval
class, this is can be achieved usingdate_create()
function. - The argument doesn’t have to order from small date to large date, we can reverse the order by placing the larger date to the first argument and the smaller date to the second argument, the result is the same.
$diff = date_diff( $end, $start );
- The result from the
date_diff()
function is theDateInterval
object, which has many properties that can be used to access the date value, e.g.d
property that returns the difference in days. In the above example, to see all the properties run the statementecho <pre>; print_r ($ diff)
Formatting the Output
DateInterval object as the result of date_diff() function has a method named format()
that can be used to produce the output with a specific format, for example:
<?php
$diff = date_diff( date_create('1988-08-10'), date_create() );
echo $diff->format('Your age is %Y years and %d days'); // Your age is 28 years and 19 days
Explanation:
- In order to the character to be translated into time, start it with a percent sign (%) in the example above are
%Y
and%d
- Year:
Y
for the four-digit year, andy
for the two digits of the years. - Month:
M
for 2-digit month, andm
to one-two digit months. - Date:
D
for 2-digit dates, andd
for one-two digit of the dates. - Today:
A
for a total different time of day. Example:$diff = date_diff(date_create ('1988-08-10'), date_create ()); echo $diff->format ('Your age is %a day'); // Your age is 10399 days.
- Hours:
H
for 2 digit hours, andh
for one-two digit hours. - Minutes:
I
for 2 digit minutes, andi
for one-two digit minutes. - Seconds:
S
for 2 digit seconds, ands
for one-two digit seconds.
Create a function to calculate date and time difference in PHP
Once we understand the easiest way to calculate date and time difference, let’s make it easier by not writing code repeatedly, to do this put our code in a function:
<?php
function diff($date1, $date2, $format = false)
{
$diff = date_diff( date_create($date1), date_create($date2) );
if ($format)
return $diff->format($format);
return array('y' => $diff->y,
'm' => $diff->m,
'd' => $diff->d,
'h' => $diff->h,
'i' => $diff->i,
's' => $diff->s
);
}
The usage example:
echo diff('1988-08-10', date('Y-m-d'), 'The difference is %y years'); // Output: The difference is 28 years;
$diff = diff('1988-08-10', date('Y-m-d'));
echo 'The difference is : ' . $diff['y'] . ' year'; // Output: The difference is 28 years
II. Calculate Date Difference in PHP – Using DateTime Object
Previously, we have calculated date and time difference in PHP using procedural style model, which uses date_diff()
function, in this section, we’ll use Object Oriented Programming (OOP) style by using the DateTime
object.
Just as date_diff()
function, the DateTime
objects only available from PHP version 5.3.0
An example:
<?php
$start = new DateTime('1988-08-10');
$end = new DateTime(); // Current date time
$diff = $start->diff($end);
echo 'The difference is ';
echo $diff->y . ' years, ';
echo $diff->m . ' months, ';
echo $diff->d . ' days, ';
echo $diff->h . ' hours, ';
echo $diff->i . ' minutes, ';
echo $diff->s . ' seconds';
// Output: The difference is 28 years, 5 months, 19 days, 20 hours, 34 minutes, 36 seconds
echo 'The difference in days : ' . $diff->days;
// Output: The difference in days : 10398
From the above example, we can conclude that this kind of model is similar to the procedural style model, yes, because, actually the date_diff()
function is an alias of DateTime::diff()
–method diff()
on the DateTime
object–
Just as date_diff()
function, DateTime
object also has a format()
method that can be used to produce a certain format. The characters used in this case is the same as the date_diff()
function
<?php
$start = new DateTime('1988-08-10');
$end = new DateTime(); //Current date time
$diff = $start->diff($end);
echo $diff->format('Your age is %Y years %d days'); // Your age is 28 years 20 days.
III. Calculate Date and Time Difference in PHP – Using Strtotime Function
Prior to PHP 5.3.0, to calculate date and time difference in PHP, we use the strtotime()
function, although it looks old school, this function remains powerful. For example:
<?php
$start = strtotime('1988-08-10');
$end = time(); // Waktu sekarang
$diff = $end - $start;
echo 'Your age is ' . floor($diff / (60 * 60 * 24 * 365)) . ' years'; // Your age is 28 years
echo 'Your age is ' . floor($diff / (60 * 60 * 24)) . ' days'; // Your age is 10400 days
In the example above, the strtotime()
function results in timestamp format. The timestamp is the kind of time format in the form of seconds counted since the epoch time (1970-01-01 00:00:00), so that the timestamp 1 means 1 seconds since epoch time or 1970-01-01 00:00:01.
Because the result is in seconds, then to calculate the time difference, we have to divide it using seconds, in the example above, to count the days, we use multiplication seconds, minutes and hours (60 x 60 x 24).
While this is more complicated than the two previous ways, this method has several advantages, which can calculate the difference in hours, minutes, seconds more easily, for example:
<?php
$start = strtotime('2017-08-10 10:05:25');
$end = strtotime('2017-08-11 11:07:33');
$diff = $end - $start;
$hours = floor($diff / (60 * 60));
$minutes = $diff - $hours * (60 * 60);
echo 'Remaining time: ' . $hours . ' hours, ' . floor( $minutes / 60 ) . ' minutes';
The above calculation will be more difficult using date_diff()
function or DateTime
Object
IV. Timezone
When we work with a date, do not forget to always adjust the timezone. Because there must be a time difference when we calculate the current time. This is because by default PHP will use it’s own timezone that usually European timezone
To change the timezone, we can use the date_default_timezone_set()
function, for example:
<?php
$start = date_create('2017-01-30 01:05:25');
$end = date_create(); // Current time, 05:40
$diff = date_diff( $end, $start );
echo $diff->h; // Result: 1
date_default_timezone_set('Asia/Jakarta');
$start = date_create('2017-01-30 01:05:25');
$end = date_create(); // Current time, 05:40
$diff = date_diff( $end, $start );
echo $diff->h; // Result: 4
The example above shows that there is a time difference between before and after defining timezone. In mine, the default PHP timezone is Europe/Berlin (GMT + 1), while my timezone is Asia/Jakarta (GMT + 7)
More about timezones can be read in the article: Understanding Timezone and Time Difference in PHP
V. Wrap Up
There are at least three ways to calculate date and time difference in PHP, that are by using the date_diff()
function, DateTime
object, and strtotime()
function.
Consider to use the date_diff()
function or DateTime
objects as they are much easier than using the strtotime()
function.
However, for certain cases, it is easier to use strtotime()
function than the other two methods.
'[ 기타 활동 ] > PHP 7' 카테고리의 다른 글
Understanding Time, Mktime, and Strtotime Function in PHP (0) | 2018.07.21 |
---|---|
Understanding Variable in PHP – All PHP Version (0) | 2018.07.21 |
Understanding Constant in PHP – Updated to PHP 7 (0) | 2018.07.21 |
Retrieve Data From MySQL Database Using PHP (0) | 2018.07.21 |
15+ Most Used PHP Array Functions You Need to Know (0) | 2018.07.21 |