LogoNavigate back to the homepage

You should know the tricks of Carbon

Yish
July 30th, 2020 · 1 min read

For my situations, I need to set period time finishing our project logics, but here is a problem, how can I mock the now from my setting? Fortunately, the php package Carbon provides a few methods to do this.

1$knownDate = Carbon::create(2001, 5, 21, 12); // create testing date
2Carbon::setTestNow($knownDate); // set the mock (of course this could be a real mock object)
3echo Carbon::getTestNow(); // 2001-05-21 12:00:00
4echo Carbon::now(); // 2001-05-21 12:00:00
5echo new Carbon(); // 2001-05-21 12:00:00
6echo Carbon::parse(); // 2001-05-21 12:00:00
7echo new Carbon('now'); // 2001-05-21 12:00:00
8echo Carbon::parse('now'); // 2001-05-21 12:00:00
9echo Carbon::create(2001, 4, 21, 12)->diffForHumans(); // 1 month ago
10var_dump(Carbon::hasTestNow()); // bool(true)
11Carbon::setTestNow(); // clear the mock
12var_dump(Carbon::hasTestNow()); // bool(false)
13echo Carbon::now(); // 2020-07-28 06:16:09

Next, our period can’t overflow a month or a year, for example, when the time is 2019-01-31 for now, I used addMonth than expected 2019-02-28, but no, because the year isn’t leap year, right? So Carbon was automatic to avoid and overflow the month to be 2019-03-03. We can use addMonthsNoOverflow and addYearsNoOverflow to get correct value of time.

1$knownDate = \Carbon\Carbon::create(2019, 1, 31);
2\Carbon\Carbon::setTestNow($knownDate);
3
4now()->addMonthNoOverflow() // 2019-02-28
5
6$knownDate = \Carbon\Carbon::create(2020, 2, 29); // leap year
7\Carbon\Carbon::setTestNow($knownDate);
8
9now()->addYearNoOverflow() // 2021-02-28

And also it provides a ton of methods, you can find on documentation.

How do I make the method of naming more semantic? Maybe you need tomorrow you do addDay or addDays(1), but internal basic class, provides many semantic methods for you.

1Carbon::tomorrow()
2Carbon::yesterday()

Comparison is frequency in use, we can use a lot of helpers.

1Carbon::isSameDay()
2Carbon::eq() = Carbon::equalTo()
3Carbon::lte() = Carbon::lessThanOrEqualTo()
4Carbon::gte() = Carbon::greaterThanOrEqualTo()

Give it a try.

More articles from Yish

Python learning resources

I wanna to learn about algorithms and how to thinking flexible, but the courses is implementing python, so I'm quickly learn about python, here are I learn resources.

June 15th, 2020 · 1 min read

A day in the life of an engineer and what tooling do I use for my work?

This article is showing my schedule daily, my job is programming for web services and data structure, also I’m going to show you about my tooling and service to assist my work.

May 2nd, 2020 · 1 min read
© 2019–2020 Yish
Link to $https://twitter.com/yishlaiLink to $https://github.com/Mombuyish