Last active
December 26, 2015 07:19
-
-
Save devoto13/7114740 to your computer and use it in GitHub Desktop.
PHP: format relative date
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 | |
function formatDate($date, $point = 'now') { | |
$point = date_create($point); | |
$date = date_create_from_format('Y-m-d H:i:s', $date); | |
$interval = date_diff($point, $date); | |
$delta = $point->getTimestamp() - $date->getTimestamp(); | |
$SECOND = 1; | |
$MINUTE = 60 * $SECOND; | |
$HOUR = 60 * $MINUTE; | |
$DAY = 24 * $HOUR; | |
$MONTH = 30 * $DAY; | |
$YEAR = 12 * $MONTH; | |
if ($delta < 0) { | |
return "not yet"; | |
} | |
if ($delta == 0) { | |
return 'just now'; | |
} | |
if ($delta == 1) { | |
return "one second ago"; | |
} | |
if ($delta < 1 * $MINUTE) { | |
return sprintf("%d seconds ago", $interval->format('%s')); | |
} | |
if ($delta < 2 * $MINUTE) { | |
return "a minute ago"; | |
} | |
if ($delta < 1 * $HOUR) { | |
return sprintf("%d minutes ago", $interval->format('%i')); | |
} | |
if ($delta < 2 * $HOUR) { | |
return "an hour ago"; | |
} | |
if ($delta < 1 * $DAY) { | |
return sprintf("%d hours ago", $interval->format('%h')); | |
} | |
if ($delta < 2 * $DAY) { | |
return "yesterday"; | |
} | |
if ($delta < 1 * $MONTH) { | |
return sprintf("%d days ago", $interval->format('%d')); | |
} | |
if ($delta < 2 * $MONTH) { | |
return "one month ago"; | |
} | |
if ($delta < 1 * $YEAR) { | |
return sprintf("%d months ago", $interval->format('%m')); | |
} | |
if ($delta < 2 * $YEAR) { | |
return "one year ago"; | |
} | |
return sprintf("%d years ago", $interval->format('%y')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment