CARBON ISN’T JUST FOR LARAVEL – PHP DATE THE RIGHT WAY

carbon-laravel-php-date

CARBON ISN’T JUST FOR LARAVEL – PHP DATE THE RIGHT WAY

The amount of times I see people having problems with PHP and DATETIME, you wouldn’t believe it. I am constantly tending to questions on Stackoverflow about issues with DateTime() or Strtotime() and usually my answer is CARBON. Carbon is nice, it ships with Laravel so I’ve become accustom to using it, but I also use it in custom applications too! If you use Composer, it’s so easy to install and instantiate, why wouldn’t you?

 

Carbon is a PHP API Extension for DateTime and it’s very, very powerful. You can use pre-defined constants such as the below to easily produce results for any day, week, month, year or century and it doesn’t stop there!

 

var_dump(Carbon::SUNDAY); // int(0)
var_dump(Carbon::MONDAY); // int(1)
var_dump(Carbon::TUESDAY); // int(2)
var_dump(Carbon::WEDNESDAY); // int(3)
var_dump(Carbon::THURSDAY); // int(4)
var_dump(Carbon::FRIDAY); // int(5)
var_dump(Carbon::SATURDAY); // int(6)	                      

Not enough for you? How about some of this!?

 

var_dump(Carbon::YEARS_PER_CENTURY); // int(100)
var_dump(Carbon::YEARS_PER_DECADE); // int(10)
var_dump(Carbon::MONTHS_PER_YEAR); // int(12)
var_dump(Carbon::WEEKS_PER_YEAR); // int(52)
var_dump(Carbon::DAYS_PER_WEEK); // int(7)
var_dump(Carbon::HOURS_PER_DAY); // int(24)
var_dump(Carbon::MINUTES_PER_HOUR); // int(60)
var_dump(Carbon::SECONDS_PER_MINUTE); // int(60)                      

This API is so flexible, I highly suggest you check out the documentation. The amount of time it has saved me is impressive. Here are D3, we do a lot of eCommerce work, be it in Laravel, WordPress, Drupal or custom and we have to store purchase dates, expiry dates, end dates, sale commence dates and so on, the list is endless! Now, lets say you say to me; “I’d like you to create a coupon code for me that does X,Y and Z, but it needs to expire next Friday”, well, I’m going to need to store that expiry date in the database and looking up next Fridays date is for chumps!

 

use Carbon\Carbon;
Carbon::parse('next friday')->toDateString()                     

That’ll do it. But what’s the time right now? Carbon::now(), what’s the date and time 5 days from now? Pfft. Easy; Carbon::now()->addDays(5).

 

Carbon provides loads of useful functions, right down to checking if it’s your birthday;

 

$born = Carbon::createFromDate(1992, 11, 27);
$fakeBirthdayToday = Carbon::createFromDate(2015, 11, 27);
$anyOtherDay = Carbon::createFromDate(2015, 11, 26);      

var_dump($born->isBirthday($anyOtherDay)); // bool(false)
var_dump($born->isBirthday($fakeBirthdayToday)); // bool(true)               

I’m a total Carbon fanboy and I highly recommend that you use it!