Gustavo Straube
Gustavo Straube

Reputation: 3861

How to check if a Carbon date object is at the start of day?

I'm using Carbon to manipulate dates I retrieved from my MySQL database. I have dates like the following:

As you can see, the first is the start of a day. When displaying dates like that, I would like to omit the time part. I know I can use a different format for each one. For example:

What I couldn't accomplish is a simple way to check if a date has a time part to apply one format or the other. Must I use individual getters to check the hour, minute and second?

Upvotes: 14

Views: 35167

Answers (3)

SeparateReality
SeparateReality

Reputation: 980

In the meanwhile its even easier. Use the is....() methods (see carbon comparison) like this:

$date = Carbon::now();
if($date->isStartOfDay()) {     // check if hour is 00:00:00
    // whatever
}

Upvotes: 6

Dekel
Dekel

Reputation: 62556

You can use the timestamp of the Carbon object minus the timestamp of "today" (which is yyyy-mm-dd 0000:00:00) and it will give you the number of seconds that passed from 00:00 to that date:

$secondsPassed = $carbonObject->timestamp - $carbonObject->copy()->startOfDay()->timestamp;
if ($secondsPassed > 8 * 60 * 60) {
    // time is passed 08:00 am
} 

Upvotes: 1

aynber
aynber

Reputation: 23010

If you just want to check if it's the start of the day, then it's fairly easy to check with Carbon's startOfDay() modifier and a comparison:

$date = Carbon::now(); // or whatever you're using to set it
$start = $date->copy()->startOfDay();
if($date->eq($start)) {
    // do your formatting here
}

Upvotes: 38

Related Questions