How to get Time ago and Days left using php script

Here i am going to show how to get time ago details and days left details using php script.Time ago is for that activity time, which has been done some time before and the days left function is for that activity time, which is still pending. Here is the how both codes looks.

1.) Time ago function.

function timeAgo($timeAgo)
{
$timeAgo = strtotime($timeAgo);
$curTime = time();
$timeElapsed = $curTime - $timeAgo;
$seconds = $timeElapsed;
$minutes = round($timeElapsed / 60);
$hours = round($timeElapsed / 3600);
$days = round($timeElapsed / 86400);
$weeks = round($timeElapsed / 604800);
$months = round($timeElapsed / 2600640);
$years = round($timeElapsed / 31207680);
/* Seconds  Calculation*/
if ($seconds <=60) {
return'Just Now';
} /* Minutes */
elseif ($minutes <=60) {
if ($minutes ==1) {
return"One Minute ago";
} else {
return $minutes." time ago minutes";
}
} /* Hours */
elseif ($hours <=24) {
if ($hours ==1) {
return"One hour ago";
} else {
return $hours." Hour Ago";
}
} /* Days */
elseif ($days <=7) {
if ($days ==1) {
return"One day ago";
} else {
return $days." days ago";
}
} /* Weeks */
elseif ($weeks <=4.3) {
if ($weeks ==1) {
return"One week ago";
} else {
return $weeks." week ago";
}
} /* Months */
elseif ($months <=12) {
if ($months ==1) {
return"One month ago";
} else {
return $months." month ago";
}
} /* Years */
else {
if ($years ==1) {
return"One year ago";
} else {
return $years." year ago";
}
}
}
2.) Days left function.
function daysleft($time)
{
$result = null;
$toDate = strtotime($time);  /*Future date*/.
$curDate = strtotime(date('Y-m-d'));
$timeleft = $toDate - $curDate;
$daysleft = round((($timeleft / 24) / 60) / 60);
if ($daysleft ==1) {
$result = $daysleft . ' ' . "Day" . ' ' . "left";
} else if ($daysleft > 1) {
$result = $daysleft . ' ' . "Day" . ' ' . "left";
} else if ($daysleft == -1) {
$result = $daysleft . ' ' . "Day" . ' ' . "Gone";
} else if ($daysleft > -1) {
$result = $daysleft . ' ' . "Day" . ' ' . "Gone";
}
return $result;
}
Note: Set date_default_timezone_set() before you using both functions so that you will get correct time information.
Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – let us know. We’d love to help!

I am Hitesh from Jamshedpur (India). I have been working as a Web Application Developer from last 4+ years. I love diverse and attention catching web presence for a variety of users. Also I love to learn new things in Web Development.

Tags: , , ,