LoginSignup
2
6

More than 5 years have passed since last update.

Carbonでの時刻比較

Last updated at Posted at 2016-12-11

Carbonとは

日付や時刻を簡単に扱うことができるPHPのAPI。

この機能はCarbonにはないのか?

現在の時間(日付なし)を取得して、その時間は大学の授業の何限に当たるかを調べるという機能を実装したかった。
1限なら8:30~10:15の間だが、betweenメソッドを用いると引数の日付ごと比較されてしまい、時間のみの比較ができないようで、うまくいかなかった。
仕方なく次のような実装にした。

$dt = Carbon::now();
$nowtime = $dt->hour * 60 + $dt->minute;
$period = 0; //以下のifに引っかからなかったら授業時間外。
if (8 * 60 + 30 < $nowtime and $nowtime < 10 * 60 + 15) $period = 1;
 //1限の時間中なら$periodに1を代入。以下同様。
if (10 * 60 + 25 < $nowtime and $nowtime < 12 * 60 + 10) $period = 2;
if (13 * 60 < $nowtime and $nowtime < 14 * 60 + 45) $period = 3;
if (14 * 60 + 55 < $nowtime and $nowtime < 16 * 60 + 40) $period = 4;
if (16 * 60 + 50 < $nowtime and $nowtime < 18 * 60 + 35) $period = 5;

Carbonに日付は関係なく時間だけを比較するメソッドは用意されてないんですかね。
ご存知の方がいれば教えてください。

(追記)
コメントをくださった方の助言で解決しました!
ありがとうございます!

2
6
2

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
2
6