PHP,Joomla,WordPress & Linux based server management, error resolutions and fixing problems.

Saturday, October 6, 2012

PHP Get time difference in Hour,Minutes or Seconds.

Starting from PHP 5.3,it has became so much easy for the programmers to code less and get more because of the in-built classes that came with it.One of from those classes is the DateTime() class which made it lot more easier for using it in many different ways,one of the most required technique from this class is getting the difference of time in Years,months,days,hours or even seconds :).

How to get time difference in PHP?

So lets start, we have a scenario that we want to actually get the difference between a past date,suppose a past date you want to compare it with the current date, initiate the class:

$today new DateTime(date('y-m-d h:m:s'));

First we need to get the today's time, Year-Month-Date Hour:Minute:Seconds , so in this way we can totally compare the past time and get the actual difference in every possible way :). Next,

$pastDate $today->diff(new DateTime('2012-09-11 10:25:00'));

Next we are going to compare the past time with the current, so using the DateTime()'s method diff() , since $pastDate is a DateInterval object.

Now you can get the years,months,days,hours or minutes and vice versa, by the following method:

echo $pastDate->y//return the difference in Year(s).
echo $pastDate->m//return the difference in Month(s).
echo $pastDate->d//return the difference in Day(s).
echo $pastDate->h//return the difference in Hour(s).
echo $pastDate->i//return the difference in Minute(s)
echo $pastDate->s//return the difference in Second(s). ​​​

So, now you can actually get the total difference in anyway you want,even in seconds.
Comments are welcome, hope you have learnt these small tricks,and in a way they are allot more helpful!

♥ Happy Coding! ♥

, , ,