Created
September 1, 2016 03:23
-
-
Save yudaprawira/54fe71ee16511ae64058399b1e8f5cbf to your computer and use it in GitHub Desktop.
PHP Time Ago
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Build Time Ago PHP | |
* @param $dateTime format Y-m-d H:i;s | |
* @return $string | |
**/ | |
function timeAgo($dateTime) | |
{ | |
$etime = time() - strtotime($dateTime); | |
if ($etime < 60) | |
{ | |
return "Just now"; | |
} | |
$a = array( 365 * 24 * 60 * 60 => "year", | |
30 * 24 * 60 * 60 => "month", | |
24 * 60 * 60 => "day", | |
60 * 60 => "hour", | |
60 => "minute", | |
1 => "second" | |
); | |
$a_plural = array( "year" => "years", | |
"month" => "months", | |
"day" => "days", | |
"hour" => "hours", | |
"minute" => "minutes", | |
"second" => "seconds" | |
); | |
foreach ($a as $secs => $str) | |
{ | |
$d = $etime / $secs; | |
if ($d >= 1) | |
{ | |
$r = round($d); | |
return $r . " " . ($r > 1 ? $a_plural[$str] : $str) . " ago"; | |
} | |
} | |
} | |
?> | |
<html> | |
<head> | |
<title>Time Ago</title> | |
</head> | |
<body> | |
<form method="POST"> | |
<input type="text" name="date" value="<?= isset($_POST['date']) ? $_POST['date'] : date("Y-m-d H:i:s", strtotime("-5 minutes")) ?>" /> | |
<button type="submit">SUBMIT</button> | |
</form> | |
<hr /> | |
<h3>RESULT</h3> | |
<?php if ( isset($_POST['date']) ) { ?> | |
Time Ago : <?= timeAgo($_POST['date']) ?> | |
<?php } ?> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment