Laravel Carbon, set specific hours:minutes:seconds
Asked Answered
F

2

19

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

Farrell answered 15/7, 2019 at 19:9 Comment(0)
H
30

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.)

Headcheese answered 15/7, 2019 at 19:11 Comment(2)
Thanks, I found on the documentation that endOfDay() method and did what I need. Nice to read the other ways too.Farrell
Important to note: All three of those RETURN an updated instance. It doesn't seem to update the instance itself. I had to do $new_days_count = $new_days_count->hour(23) in order to actually update the instance.Galvanize
E
5

Like @ceejayoz mentionned, for your use case endOfDay() is what your need.

If you encouter a use case where you need to set a specific time (i.e 22:32:05), you could use the fluent setter setTimeFromTimeString('22:32:05') instead of chaining hour(22)->minute(32)->second(5).

Elated answered 23/11, 2022 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.