Skip to content

Instantly share code, notes, and snippets.

@syropian
Created January 18, 2012 19:04
Show Gist options
  • Save syropian/1634946 to your computer and use it in GitHub Desktop.
Save syropian/1634946 to your computer and use it in GitHub Desktop.
Relative Date Class
<?php
class Date {
public static function torelative($date) {
$diff = strtotime('-1 day') - strtotime($date);
if ($diff>0) {
if ($diff<60)
return $diff . " second" . self::plural($diff) . " ago";
$diff = round($diff/60);
if ($diff<60)
return $diff . " minute" . self::plural($diff) . " ago";
$diff = round($diff/60);
if ($diff<24)
return $diff . " hour" . self::plural($diff) . " ago";
$diff = round($diff/24);
if ($diff<7)
return $diff . " day" . self::plural($diff) . " ago";
$diff = round($diff/7);
if ($diff<4)
return $diff . " week" . self::plural($diff) . " ago";
return "on " . date("F j, Y", strtotime($date));
} else {
if ($diff>-60)
return "in " . -$diff . " second" . self::plural($diff);
$diff = round($diff/60);
if ($diff>-60)
return "in " . -$diff . " minute" . self::plural($diff);
$diff = round($diff/60);
if ($diff>-24)
return "in " . -$diff . " hour" . self::plural($diff);
$diff = round($diff/24);
if ($diff>-7)
return "in " . -$diff . " day" . self::plural($diff);
$diff = round($diff/7);
if ($diff>-4)
return "in " . -$diff . " week" . self::plural($diff);
return "on " . date("F j, Y", strtotime($date));
}
}
public static function plural($num) {
$num = abs((int) $num);
if ($num != 1)
return "s";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment