Carbon trick: set now() time to whatever you want

Tutorial last revisioned on August 18, 2022 with Laravel 9
Quite often the logic of our applications rely on the current time. For example, if it's weekend, or if it's past midday or something. We usually use Carbon::now() to check the time - but what if it's morning now, and we need to test if it's 5 PM already? Do we really need to wait till evening to test the function? No. Carbon has a trick for that. There's a function called Carbon::setTestNow() where you can set the parameter of whatever you want. Examples:
$knownDate = Carbon::create(2001, 5, 21, 12);
echo Carbon::now();  // will show 2001-05-21 12:00:00
What it does is "faking" now() time, allowing you to test the functionality with real-time, without waiting. If you want to clear "fake" time, just call same function without parameters:
Also you can test, if there's "fake" time set:
if (Carbon::hasTestNow()) { // ...
Also, remember that Carbon can parse data in a lot of formats, like this:
Carbon::setTestNow(Carbon::parse('first day of March 2015'));
In general, I recommend that you read through Carbon documentation - there's a lot of "hidden gems" and useful functions.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by

You might also like