I have this function which calculates how many seconds, mins, hours etc ago a specific time string was.
However, the way I have done it consists of a massive if statement block, and it goes through each specific time that it can reach.
Is there a better way of writing this code where it's more efficient and doesn't have a massive if statement block?
define('SECS_IN_MIN', 60);
define('SECS_IN_HR', 3600);
define('SECS_IN_DAY', 86400);
define('SECS_IN_WEEK', 604800); // 7 days
define('SECS_IN_MONTH', 2592000); // 30 days
define('SECS_IN_YEAR', 31536000); // 365 days
// Determines if a number is a plural
// Input: Takes in a number
// Output: Outputs a string which is either "s", if plural
// OR "" if not plural
function is_plural($num) {
if ($num != 1) return "s";
else return "";
}
// Gets a string line x minutes ago
// Input a date
// Output: a string which matches its time ago
function date_to_str($time) {
$currTime = time();
$pastTime = strtotime($time);
$diff = $currTime - $pastTime;
// Seconds Ago
if ($diff < SECS_IN_MIN) {
$plural = is_plural($diff);
return "$ans few second$plural ago";
// Minutes Ago
} else if($diff < SECS_IN_HR) {
$ans = floor($diff / SECS_IN_MIN);
$plural = is_plural($ans);
return "$ans minute$plural ago";
// Hours Ago
} else if ($diff < SECS_IN_DAY) {
$ans = floor($diff / SECS_IN_HR);
$plural = is_plural($ans);
return "$ans hour$plural ago";
// Days Ago
} else if ($diff < SECS_IN_WEEK) {
$ans = floor($diff / SECS_IN_DAY);
$plural = is_plural($ans);
return "$ans day$plural ago";
// Weeks ago
} else if ($diff < SECS_IN_MONTH) {
$ans = floor($diff / SECS_IN_WEEK);
$plural = is_plural($ans);
return "$ans week$plural ago";
// Months Ago
} else if ($diff < SECS_IN_YEAR) {
$ans = floor($diff / SECS_IN_MONTH);
$plural = is_plural($ans);
return "$ans month$plural ago";
// Years Ago
} else if ($diff > SECS_IN_YEAR * 10) {
$ans = floor($diff / SECS_IN_YEAR);
$plural = is_plural($ans);
return "$ans year$plural ago";
}
return "-1";
}
$time = "2020-08-25 13:02:32"
echo( date_to_str($time) );
// Outputs 4 days ago