logo
podcast Podcast
get help Get Unstuck

Some unexpected behavior with times in Carbon

As always, it pays to be explicit

Joel Clermont
Joel Clermont
2024-08-05

I always try to be as explicit as possible in my tests. It might make the test just a little bit longer, but it also makes the test much more readable and predictable, two qualities I really value in a test suite.

One example I want to share today is with Carbon dates, especially the time component of the value.

In the following example, note the subtle differences with the time component when generating relative date strings:

// 2023-09-01 02:26:17.036945 - this format appends the current time of day
Carbon::parse('first day of next month');

// 2023-09-01 00:00:00.000000 - this format sets it to midnight
Carbon::parse('first day of September');

// no ambiguity here at all
Carbon::parse('2023-09-01 00:00:00');

That last example leaves absolutely nothing to the imagination, and has no surprising behavior.

To demonstrate the point even further, this time behavior gets even more unexpected if you use the Carbon::setTestNow() helper:

// setting a test time will change behavior subtly from the previous example
Carbon::setTestNow('2023-08-04 21:00:01');

// 2023-09-01 21:00:01.000000 - matches our test time, makes sense so far...
Carbon::parse('first day of next month');

// 2023-09-01 21:00:01.000000 - but this is no longer midnight anymore!
Carbon::parse('first day of September');

I'm not saying there is never a reason to use relative dates in tests, but I would make sure it's contributing to the readability of the test, and not possibly introducing some unexpected behavior.

Here to help,

Joel

P.S. Like so much I share in this newsletter, this is a lesson I learned the hard way. If you'd like to jump start your team with testing, I'd love to discuss it with you.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.