Friday 6 September 2019

PHP Tutorial | Display Days : Hours : Minutes : Seconds Between Two Dates


Code : 

<h1>

<center>

<?php

$current_date_time_sec=strtotime("2019-8-31 03:45:00");


$future_date_time_sec=strtotime("2019-9-3 00:00:00");


$difference=$future_date_time_sec-$current_date_time_sec;


$hours=($difference / 3600);


$minutes=($difference / 60 % 60);


$seconds=($difference % 60);


$days=($hours/24);


$hours=($hours % 24);


echo "The difference is <br/>";


if($days<0)

{

echo ceil($days). " days AND ";

}

else

{

echo floor($days). " days AND ";

}


echo    sprintf("%02d",$hours).":".sprintf("%02d",$minutes).":".sprintf("%02d",$seconds);


?>

</center>

</h1>




Hello guys.
This tutorial will be about how to get difference between two dates in days,hours,minutes,seconds format.
Lets start code with a scratch.
You have to call a function str_to_time, make sure to provide date-time format same as in the video.
This function gives the number of seconds of each date.
Now we have to calculate the diffrence.
There are formulas for calculating days, minutes, using seconds.
Make sure you type them as it is.
Now the problem is, single digit doesn’t look good, so we have to convert it using sprintf function.
This function will have two argument, 1st for formatting, and 2nd for value.
I forgot to give zero before 2.
Lets try using different numbers.
All good.
Now 49 hours means, 2 days and 1 hour extra.
So, for that, apply other formulas.
We have to overwrite the hour variable.
You see that, the days are in decimal.
So to make it easy to understand, if days are -ve, then use ceil, and if days are +ve, then use floor.
Lets, test it using different dates.
The code is in the description.
Thank you for watching, dont forget to like share and subscribe.

Please avoid or flag spams/hateful comments. And do not spam. Enjoy :)


Subscribe my Channel:-
http://www.youtube.com/user/SanketRooney?sub_confirmation=1

Facebook Page:-
https://www.facebook.com/UnpossibleNS

Twitter Account:-
https://twitter.com/UnpossiblePOG

Blog :-
https://unpossiblepog.blogspot.in/

No comments:

Post a Comment