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
Post a Comment