Skip to main content

How to calculate time(Seconds, Minutes, Hours, days , Years) from current date or days in PHP?

Calculate time(Seconds, Minutes, Hours, days , Years) from current date or days in PHP.

 

<!DOCTYPE html>

<html>

<body>


<?php

function calculate_time($old_date){

$current_time = date('Y-m-d H:i:s');

$date1 = new DateTime($old_date);

$date2 = $date1->diff(new DateTime($current_time));

//print_r($date2);

//echo $date2->days.'Total days'."\n";

$years = $date2->y;

$months = $date2->m;

$days = $date2->d;

$hours = $date2->h;

$min = $date2->i;

$sec = $date2->s;

if(!empty($years) && $years>0){

if($years == 1){

$cal_time = $years.' Year';

}

else{

$cal_time = $years.' Years';

}

}

elseif(!empty($months) && $months>0){

if($months == 1){

$cal_time = $months.' month';

}

else{

$cal_time = $months.' months';

}

}

elseif(!empty($days) && $days>0){

if($days == 1){

$cal_time = $days.' day';

}

else{

$cal_time = $days.' days';

}

}

elseif(!empty($hours) && $hours>0){

if($hours == 1){

$cal_time = $hours.' hour';

}

else{

$cal_time = $hours.' hours';

}

}

elseif(!empty($min) && $min>0){

if($min == 1){

$cal_time = $min.' Minute';

}

else{

$cal_time = $min.' Minutes';

}

}

elseif(!empty($sec) && $sec>0){

if($sec == 1){

$cal_time = $sec.' secend';

}

else{

$cal_time = $sec.' secends';

}

}

return $cal_time;


}

echo calculate_time('2021-04-13 00:7:51').' ago';

?>


</body>

</html>


Comments

Popular posts from this blog

How to check date format in PHP?

Check date format in PHP function isCorrectDateFromat($date){     if(!empty($date)){         $dateString = $date; // Replace this with your date string         $format = "Y-m-d"; // Replace this with your expected date format         $dateTime = DateTime::createFromFormat($format, $dateString);         if ($dateTime === false) { /*             echo "The date is not in the correct format."; */         } else {             $errors = DateTime::getLastErrors();             if (empty($errors)) { /*                 echo "The date is in the correct format."; */                 return true;             } else { /*                 echo "...