Created
July 25, 2013 22:59
-
-
Save hirak/6084531 to your computer and use it in GitHub Desktop.
Twitter風の「約○○分前」を計算する ref: http://qiita.com/Hiraku/items/7264ab40bfad3b50819a
This file contains hidden or 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 | |
/** | |
* Twitter風の「約○○分前」を計算する関数 | |
* @param DateTime $target | |
* @param DateTime $now 基準時間をずらしたい場合に指定。 | |
* @return string | |
*/ | |
function toLastUpdateString(DateTime $target, DateTime $now=null) | |
{ | |
if (!$now) $now = new DateTime('@' . $_SERVER['REQUEST_TIME']); | |
$diff = $target->diff($now); | |
if ($diff->invert) { | |
trigger_error('$targetが$nowより未来になっています'); | |
return '今さっき'; | |
} | |
if ($diff->y) return $diff->y . '年前'; | |
if ($diff->m) return $diff->m . 'ヶ月前'; | |
if ($diff->d) return $diff->d . '日前'; | |
if ($diff->h) return $diff->h . '時間前'; | |
if ($diff->i) return $diff->i . '分前'; | |
if ($diff->s) return $diff->s . '秒前'; | |
return '今さっき'; | |
} | |
//テスト | |
echo toLastUpdateString(new DateTime('- 1 minutes')), PHP_EOL; | |
echo toLastUpdateString(new DateTime('yesterday')), PHP_EOL; | |
echo toLastUpdateString(new DateTime('last week')), PHP_EOL; | |
echo toLastUpdateString(new DateTime('last month')), PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment