Search code examples
laravelphp-carbon

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


Solution

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