14

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

  • 2017-07-19 00:00:00
  • 2017-06-26 15:27:57

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:

  • F d Y for dates without time.
  • F d Y g:ia for dates with time.

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?

1
  • It is start of the day and end of the previous day. Commented Aug 22, 2017 at 19:09

3 Answers 3

37

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
}
2
  • Hey, @aynber. This is an interesting approach. In terms of code styling, it's better than check each time property (hour, minute and second). Commented Aug 22, 2017 at 19:28
  • Carbon has some great functions for modifying and comparing dates and time. The links I provided are for the Carbon docs, and you can see all of the different functions.
    – aynber
    Commented Aug 22, 2017 at 20:00
6

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
}
1
  • 1
    Probably this function didn't exist at the time I posted the question, 2 years ago. Thank you anyway. Commented Dec 5, 2019 at 12:04
1

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
} 
2
  • Hey, @Dekel. Thanks, but it seems that will work only for dates in the current day. Commented Aug 22, 2017 at 19:26
  • You are right, answer updated. Changed the today to the startOfDay() of the CarbonObject you have
    – Dekel
    Commented Aug 22, 2017 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.