Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PeterF's avatar

Best practice for TIME with no DATE

Just polling the crowd on how you all do time with no date?

Obviously everything in Laravel ends up being very Carbon centric, but I find myself setting dates almost randomly, to make sure that my "time" does indeed appear between the start_time and end_time, because Carbon has put dates on them, and then it turns out 3pm is not between 1pm and 4pm, because I am suddenly looking at a different day.

How does everyone else deal with this? Have I just missed the really obvious time-only class?

0 likes
7 replies
tykus's avatar

There is no such thing as time without a date for exactly the reason you describe "it turns out 3pm is not between 1pm and 4pm, because I am suddenly looking at a different day". If you want to compare, evaluate, differentiate to different Time instances, you need to know the date-part of each instance (along with the timezone!).

deansatch's avatar

just store it as a unix timestamp and use strtotime() and date() to convert back and forth then you can run comparisons on the unix timestamp

PeterF's avatar

My business requirement is that I have key times of the day. 1-3pm and 4-6pm, and I want to find out if transactions are occuring in those time windows. Except that everything wants to put a date on it, so I can't check for between 1 and 3 PM, because it turns out that I must have meant TODAY, when I am actually not interested in days, I just want things between 1 and 3 on any day.... so there is time without a day. That is a thing. The question is how do people do it Laravel/Eloquent?

tykus's avatar

@PeterF but it is no time without a day because the transaction has a datetime.

You can achieve what you need using the appropriate constraints (depending on your database), e.g.

Transaction::query()
    ->whereRaw('HOUR(created_at) >= 13 AND HOUR(created_at) < 15')
    ->get();
1 like
PeterF's avatar

@tykus a-ha... this is precisely the sort of answer I was looking for.... because I was doing that, more or less, but it felt clunky..... and it always feels like a cheat or a hack, to slide out of eloquent into a whereRaw.... I feel like Laravel (and Eloquent) has everything you could ever want, so if I do a whereRaw, it just means that I have missed something that is obvious..... but what you are saying is that there is clever bit of eloquent I have missed... so thats good... thanks.

deansatch's avatar
$time1 = '15:00:00';
$time2 = '13:00:00';

User::whereTime('created_at','<', $time1)
->whereTime('created_at','>', $time2)
->pluck('created_at');
1 like

Please or to participate in this conversation.