Help us understand the problem. What is going on with this article?

PHPの日付処理ライブラリCarbonで現在時刻との差(diff)を取得する

More than 1 year has passed since last update.

現在時刻との差(diff)を取得する

YouTubeで下記の表示を見るので作ってみました。
image.png

public function getDateDiff(string $datetime): string
{
    $now    = new \Carbon\Carbon();
    $target = new \Carbon\Carbon($datetime);

    $diff_seconds = $now->diffInSeconds($target);
    if (0 <= $diff_seconds && $diff_seconds < 60) return '1分前';

    $diff_minutes = $now->diffInMinutes($target);
    if (1 <= $diff_minutes && $diff_minutes < 60) return $diff_minutes . '分前';

    $diff_hours = $now->diffInHours($target);
    if (1 <= $diff_hours && $diff_hours < 24) return $diff_hours . '時間前';

    $diff_days = $now->diffInDays($target);
    if (1 <= $diff_days && $diff_days < 7) return $diff_days . '日前';

    $diff_weeks = $now->diffInWeeks($target);
    if (1 <= $diff_weeks && $diff_weeks < 4) return $diff_weeks . '週間前';

    $diff_months = $now->diffInMonths($target);
    if (1 <= $diff_months && $diff_months < 12) return $diff_months . 'ヶ月前';

    $diff_years = $now->diffInYears($target);
    if (1 <= $diff_years) return $diff_years . '年前';

    return $target->format('Y-m-d H:i:s');
}

60秒以内のものは「1分前」としています。
下記のように書き換えれば「10秒前」のような表示ができます。

if (0 <= $diff_seconds && $diff_seconds < 60) return $diff_seconds . '秒前';

ご自由にお使いください。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away