LoginSignup
17

More than 5 years have passed since last update.

Twitter風の「約○○分前」を計算する

Last updated at Posted at 2013-07-25

PHP5.3以降ならDateIntervalを使うと楽。

<?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']);
    /** @type DateInterval $diff */
    $diff = date_diff($target, $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 minute')), 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;

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17