Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

php-carbon

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?

like image 695
Gustavo Straube Avatar asked Aug 22 '17 19:08

Gustavo Straube


People also ask

How do you find the first day of the month in Carbon?

How do you find the first day of the month in Carbon? $now = Carbon::now(); $startOfMonth = $now->startOfMonth('Y-m-d');

How do you find the difference between two dates in Carbon?

You can only use the diffInDays() function on a Carbon instance. You can create a new one by parsing the end date you're receiving. $end = Carbon::parse($request->input('end_date'));


1 Answers

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
}
like image 153
aynber Avatar answered Nov 15 '22 15:11

aynber