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

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);
Carbon::setTestNow($knownDate);     
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:

Carbon::setTestNow();

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.

Like our articles?
Check out our Laravel online courses!

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here