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:

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:

Also, remember that Carbon can parse data in a lot of formats, like this:

In general, I recommend that you read through Carbon documentation – there’s a lot of “hidden gems” and useful functions.

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

2 thoughts on “Carbon trick: set now() time to whatever you want

Leave a Reply

Your email address will not be published. Required fields are marked *