Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Carbon::setTestNow() in PHP?

For testing purposes I want to set the date to a specific date. I'm now trying to do that using the Carbon lib, but it fails to do so:

Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));
printf(date("Y-m-d H:i:s"));  // prints 2018-06-28 13:21:06

What am I doing wrong here? How can I globally set the time to a specific date?

like image 618
kramer65 Avatar asked Oct 20 '25 10:10

kramer65


1 Answers

Setting

date() is a regular PHP function that doesn't have anything to do with Carbon and Carbon::setTestNow() does not change the system clock thus it's the expected behaviour.

I presume you just want to use Carbon all the way:

Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));
echo Carbon::now();                     

Resetting

(from @Orchis in notes)

Also worth noting that Carbon::setTestNow(); can be used to reset the time in Carbon to normal, so you don't affect later tests in your suite.

like image 65
Álvaro González Avatar answered Oct 22 '25 00:10

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!