Sunday, December 11, 2016

How to Calculate Hours Between Two Dates in PHP

Hello Friends,

 Today we bought a new problem which most of the developers in php is finding  is the error of hours difference  between two date. Now as i have seen this error in depth and bought a solution for the same here in my new post.Now get back to the topic many of us face the problem of calculating the hours between two dates and google it for the same to how to solve the problem.

You have to dates and you want to calculate hours between those two dates.

Here is Source code


<?php

$date1 = "2014-05-27 01:00:00";
$date2 = "2014-05-28 02:00:00";
$timestamp1 = strtotime($date1);;
$timestamp2 = strtotime($date2);;
echo "Difference between two dates is ". $hour = abs($timestamp2 - $timestamp1)/(60*60) . " hour(s)";
?>


Here i am taking two variable one is the $date1 and $date2 as you see we have taken the two date and now we are going to calculate the difference of hours between these two dates.

Here we are using the strtotime() function of date and time in php through which we are going to find out hours in two steps.

1. Firstly, convert each date to its equivalent timestamp (as you know, timestamp is number of seconds since January 1 1970 00:00:00 UTC).
2. Secondly, Now the value of timestamp  which we save it  in the two variable such as $timestamp1 and $timestamp2. Now to get the no of Hours we are taking the difference between the two timestamp  variable above as shown in code and divide it by 60*60 to get the no of Hours.


After running the above php code you get the output like as give below.



Output: Difference between two dates is 25 hour(s)














No comments:

Post a Comment