Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Carbon, set specific hours:minutes:seconds

I have a Carbon date like:

$new_days_count = Carbon::now();

dd($new_days_count);

Carbon {#764 ▼
  +"date": "2019-07-20 19:06:49.119790"
  +"timezone_type": 3
  +"timezone": "UTC"
}

Now, I want to set a specific hours:minutes:seconds to that time, in order to have:

Carbon {#764 ▼
  +"date": "2019-07-20 23:59:59.000000"
  +"timezone_type": 3
  +"timezone": "UTC"
}

How can I set it? I want to set always at 23:59:59.000000

like image 384
pmiranda Avatar asked Jul 15 '19 19:07

pmiranda


People also ask

What is carbon :: now ()?

Carbon::now returns the current date and time and Carbon:today returns the current date. $ php today.php 2022-07-13 15:53:45 2022-07-13 00:00:00. This is a sample output. Carbon::yesterday creates a Carbon instance for yesterday and Carbon::tomorrow for tomorrow.

How do you set the date on carbon?

Carbon also allows us to generate dates and times based on a set of parameters. For example, to create a new Carbon instance for a specific date use the Carbon::createFromDate() method, passing in the year, month, day, and timezone, as in the following example.


Video Answer


1 Answers

For your specific use case, this should do:

Carbon\Carbon::now()->endOfDay()

You can also more generally use the setters:

$new_days_count->hour = 23;
$new_days_count->minute = 59;
$new_days_count->second = 59;

or

$new_days_count->hour(23);
$new_days_count->minute(59);
$new_days_count->second(59);

or $new_days_count->setHour(23) or $new_days_count->set('hour', 23). Don't ask me why there are twelve different ways of doing it; they all do the same thing, so pick the one you like the look of.

(If you really care about the microseconds, you can also do $new_days_count->micro(0) to set that to zero.)

like image 156
ceejayoz Avatar answered Dec 08 '22 18:12

ceejayoz