Skip to main content
Tutorial Free

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

December 03, 2015
1 min read

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

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.