Add function to get relative timestamp up to many years, with unit tests

This commit is contained in:
Kijin Sung 2016-05-26 16:41:20 +09:00
parent 3c72258521
commit e96ac0ba7a
5 changed files with 123 additions and 23 deletions

View file

@ -21,6 +21,11 @@ class DateTime
*/
public static function formatTimestamp($format, $timestamp = null)
{
if ($format === 'relative')
{
return self::getRelativeTimestamp($timestamp ?: time());
}
$offset = Config::get('locale.internal_timezone') ?: date('Z', $timestamp);
return gmdate($format, ($timestamp ?: time()) + $offset);
}
@ -34,6 +39,11 @@ class DateTime
*/
public static function formatTimestampForCurrentUser($format, $timestamp = null)
{
if ($format === 'relative')
{
return self::getRelativeTimestamp($timestamp ?: time());
}
$timezone = self::getTimezoneForCurrentUser();
if (!isset(self::$_timezones[$timezone]))
{
@ -164,4 +174,65 @@ class DateTime
default: return 'Etc/GMT' . ($offset > 0 ? '-' : '+') . intval(abs($offset / 3600));
}
}
/**
* Get a relative timestamp (3 hours ago, etc.)
*
* @param int $timestamp
* @return string
*/
public static function getRelativeTimestamp($timestamp)
{
$diff = \RX_TIME - $timestamp;
$langs = lang('common.time_gap');
if ($diff < 3)
{
return $langs['now'];
}
if ($diff < 60)
{
return sprintf($langs['secs'], $diff);
}
if ($diff < 60 * 2)
{
return sprintf($langs['min'], 1);
}
if ($diff < 3600)
{
return sprintf($langs['mins'], $diff / 60);
}
if ($diff < 3600 * 2)
{
return sprintf($langs['hour'], 1);
}
if ($diff < 86400)
{
return sprintf($langs['hours'], $diff / 3600);
}
if ($diff < 86400 * 2)
{
return sprintf($langs['day'], 1);
}
if ($diff < 86400 * 32)
{
return sprintf($langs['days'], $diff / 86400);
}
if ($diff < 86400 * 60)
{
return sprintf($langs['month'], 1);
}
if ($diff < 86400 * 366)
{
return sprintf($langs['months'], $diff / (86400 * 30.5));
}
if ($diff < 86400 * 732)
{
return sprintf($langs['year'], 1);
}
else
{
return sprintf($langs['years'], $diff / (86400 * 365.25));
}
}
}