Easy PHP Dates and Times With Carbon

Easy PHP Dates and Times With Carbon

PHP Dates and Times With Carbon are made incredibly simple with the intuitive API provided by this great library. Carbon extends the native PHP DateTime class which gives it access to all of the functions you are familiar with, in addition to some other great new features. Carbon makes use of it’s own namespace aptly named Carbon. When you get started, make sure to import that namespace such as use Carbon/Carbon; to get up and running quickly. Let’s take a look at some of the various things Carbon can do for us while we review instantiation, getters, setters, string formatting, common formats, differences, modifiers, and more.


Create a new Carbon Instance

The first thing we’ll do is to simply create a new instance of the Carbon class so we can have a look at what it is. We’ll do this by simply using the new operator with the Carbon class and assign it to a simple variable aptly named $carbon.

We can inspect our new object now.
var dump of carbon instance

We can see here that it is an object of the Carbon\Carbon class. The next thing we see is that there is a public property called date which is a string containing the date and the time. timezone_type is the next public property we see which is an integer with a value of 3, and a public property named timezone which is a string having the value of UTC. We’ll focus on that date property to start.


Using Carbon via Static Methods

A different approach we could use is to call static methods right off of the Carbon class without having to even new up an instance first. A useful method is the now() method. Let’s try it out right now.

Carbon::now()

var dump of carbon now method

What we find when inspecting this instance with var_dump() is that we have the same type of object as when we took the approach of using the new keyword to create a new instance of the Carbon class. One might say this approach is slightly more readable, but it doesn’t really matter which you choose.

Carbon::today()

Carbon::today() is another method you can use and is just slightly different than Cabon::now(). You can use this when you’re not so much concerned at this exact moment in time, but rather simply what day it is. As such, this method only gives you the string representation of today and omits the time. We can see this by inspecting the var_dump and noticing that the time is all zeroes.

ar dump of carbon today method

Carbon::tomorrow()

Carbon::tomorrow() is a useful method to dynamically determine the date of tomorrow. In our prior example, we saw the date as 11/11 of 2015. If this method works correctly, we should find a value of 11/12 of 2015 in our output.

carbon tomorrow method

Excellent. Notice that the date did increment by one and we see the result of 11/12 of 2015.

Carbon::yesterday()

If we can easily return the value for tomorrow, it stands we should also be able to get the value of yesterday. Alas, this is quite easy with Carbon.

carbon yesterday method

This code is working just like we would expect it would, as it returns the value of 11/10 of 2015, which is a fine day indeed.

Carbon::create()

This method would be used to create an exact date and time of your choosing. This method depends on you passing in some arguments. We can view the source of the Carbon class to see what it expects.

When using Carbon::create(), you would typically pass in the parameters of year, month, day, hour, minute, second, and timezone. We’ll test it out now.

party like its 1999

This of course represents New Years Eve which was a Friday on December 31st of 1999 with exactly one second left until “Yeah, they say two thousand zero zero party over, Oops out of time, So tonight I’m gonna party like it’s 1999, Yeah.” You get the idea.

Carbon::createFromDate()

Maybe you need to create an object just based on the date, but not the time. This method is just what you need for that.

carbon createfromdate

This gives us the same date, however the time is simply filled in with the current time rather than a specific time you provide as parameters to the method.

Carbon::createFromTime()

This method allows you to set a specific time of the current day.

carbon createfromtime

Notice that the time is reflected as the values we passed in, while the date is an instance of today.

Carbon::createFromTimestamp

If you have a timestamp you would like to create a Carbon instance from, we can use this method.

unix time 1970 01 01

This is the birthday of the Unix operating system.

Let’s try something a timestamp that might be a little more applicable. http://www.unixtimestamp.com/ gives us the number of seconds which have passed since since Jan 01 1970. Let’s go ahead and pass in a timestamp from there.

unix timestamp


Carbon For Dummies

Now that we’ve seen various ways to create an object of type Carbon, let’s look at the Creating a Carbon Instance for Dummies version. I say this because when you new up a Carbon instance, you can pass in a string in a human readable form, and Carbon is smart enough to create what you are trying to achieve. For example, we can create a specific date like so.

All of these are interpreted correctly by Carbon and PHP and provide the output like so.
carbon parent constructor

We can also pass in a string which represents something like 3 days ago or 4 days from now. In addition to this, you can specify plus or minus hours as well to get more granular. Here are a few examples.

This is pretty cool and we have covered most ways you would ever be creating an instance of Carbon manually. Now we can take a look at formatting dates with Carbon which is where Carbon really shines.


Formatting Dates and Time With Carbon

toDateString()

The first method of the Carbon class we’ll look at is toDateString(). It takes the date in the Carbon object and puts it into a nicely formatted date string.

toTimeString()

The toTimeString() method formats the time in the Carbon object to a properly formatted time string.

What happened in this example is that since we did not actually provide a time in the constructor, the current time is used at the time of the code executing. We did however have a subtraction clause, and we were removing 10 hours, so that does get reflected in the time string.

toDateTimeString()

toAtomString()

You may format the the date and time as an atom string like so.

toCookieString()

Formatting the date and time to the standard of a cookie is easy with the toCookieString() method.

toDayDateTimeString()

This is how the toDayDateTimeString() method works, and the output is very nice.

toFormattedDateString()

The toFormattedDateString() outputs your Carbon instance like so.

toIso8601String()

There are several standards based date and time formats. This one is for ISO 8601.

toRfc822String()

We have built in support for RFC 822 via the toRfc822String() method.

toRfc850String()

Get your RFC 850 formatted strings out of your Carbon object with the toRfc850String() method.

toRfc1036String()

Formatting RFC 1036 date time is a breeze with the toRfc1036String() method.

toRfc1123String()

This is how you can set the format to an RFC 1123 string.

toRfc2822String()

Are you in need of an RFC 2822 formatted string? You are in luck with the toRfc2822String() method.

toRfc3339String()

Maybe RFC 3339 is what you are looking for. The toRfc3339String() method is the one you need.

toRssString()

The toRssString() method quickly formats the date time to something compliant with an RSS feed.

toTimeString()

The toTimeString() method offers a way to output a very simple format like so.

toW3cString()

Easily format to the W3C string format with the toW3cString() method.

All of these methods begin with to as we can see here. There is a bit of overlap between the names of the methods and the formats they provide, but what this does is allow you to structure your code in a way that makes the most sense possible to you. In other words, you have enough sugar to make things easier to reason about during development.

Now you might be thinking about the standard way we format dates in PHP when using things like strtotime(), DateTime and date_create() in native PHP. The same rules apply for Carbon, and if you prefer, you can simply use the format() method like so.

Behold diffForHumans() !

This is one of the coolest methods in the Carbon Library. What it does is to compare the current date and time to that which is stored in the current instance of Carbon. For example, the Carbon instance itself may hold a timestamp or some format of date and time from a few days ago, or perhaps even something in the future. The diffForHumans() method creates really nicely formatted and human readable formats from this difference in time. Let’s see a few examples.


Carbon Getters

We already had a look at all of the ways we can format dates and times with Carbon. Now what happens if you want to access say just the day, or just the hour, or just the minute you are interested in? Do you re format the Carbon instance and then retrieve the values as you want? No you don’t have to do that, you can make use of the special getter methods which will retrieve dates and times in the format you like. Let’s take a look at the source code that makes this possible, since it will enlighten us on how Carbon is actually working it’s magic.

Getter Functionality

This code now makes it extremely easy and convenient to do things like we see here giving us quick access to the integer values of all of the various parts of a date time.


Carbon Setters

Just as we have getters we can work with in Carbon to make things easier for us, Carbon also provides a nice Setter functionality. Using setters in Carbon is like another way to create an instance of a date time in Carbon. Sometimes it is easier to explicitly set the year month day or hour manually, rather than to figure out how to properly pass in the right format to do so. Let’s have a look at the Carbon source code which makes these setters possible. We can see that it has support for setting the year, month, day, hour, minute, second, timestamp, and timezone. If you pass in something the code does not understand, it will throw an exception.

Setter Functionality

Now consider we new up a Carbon instance like so.

We can inspect that instance and confirm it is what we might expect.
carbon instance

What happens however when we go ahead and set some of the values in that Carbon instance? Let’s find out! We will new up the instance, set some properties, then var dump it and also output the result as a formatted string.

carbon setters

So we see that we can easily set values on our Carbon instance and update it with ease.


Carbon Timezone

Carbon makes working with Timezones in PHP really easy. You can interact with timezones in Carbon via the property $timezone and it’s alias $tz. You will need to make sure however, that you are using one of the supported timezones in PHP. For example, here is the list of supported timezones in America. With this knowledge, let us set up a new Carbon instance with the Time Zone of New York City.

carbon timezone

Another way you might tackle implementing a Time Zone in Carbon is like so.

If you would rather use a method instead of passing in an argument, you can also complete setting the time zone this way as well. Here are a few more ways we might to this.

So we can see that Carbon is quite flexible, and you have several ways to accomplish the same task.


Manipulating Date and Time with Carbon

When you need to manipulate Dates and Times in raw PHP, things can get a bit messy. Carbon provides all kinds of useful methods that will take care of all the messy calculations for you and allows you to easily manipulate dates and times using much more readable syntax.

Add Days Using Carbon

carbon add methods

Subtract Days Using Carbon

Just as we can easily add a given number of days to a Carbon object, we can just as easily subtract days.

carbon subtract methods

This is really so slick. We can see that Carbon takes care of everything for us. If we happen to add so many days that it is going to go into the next month, Carbon is smart enough to adjust the month as well. There are a ton more methods you can use such as add(), addDay(), addDays(), addHour(), addHours(), addMinute(), addMinutes(), addMonth(), addMonthNoOverflow(), addMonths(), addMonthsNoOverflow(), addSecond(), addSeconds(), addWeek(), addWeekday(), addWeekdays(), addWeeks(), addYear(), addYears(), sub(), subDay(), subDays(), subHour(), subHours(), subMinute(), subMinutes(), subMonth(), subMonthNoOverflow(), subMonths(), subMonthsNoOverflow(), subSecond(), subSeconds(), subWeek(), subWeekday(), subWeekdays(), subWeeks(), subYear(), and subYears(). That’s a lot of methods to work with! Your best bet would be to test them out for yourself, and see what works best for your particular application.


Comparing Dates and Times in Carbon

Carbon allows you to compare two instances of Carbon in different ways to see how they relate. Are they greater than, less than, equal to, and so on. The best way to have a look at how this works is to just whip up a few examples.

Checking Date Equality

Checking Greater Than Values

Checking Less Than Values

We can see how the gt(), lt(), and eq() methods work which allow us to quickly check for equality between two dates. In addition you can use the gte() and lte() methods if you need to check for a greater than or equal to, and less than or equal to situation.

Checking Between Dates With Carbon

We have a nice between() method for checking where a date exists between two given dates. Let’s see how this works.


Checking Date and Time Differences with Carbon

Calculating differences in dates is a very useful application that you can take advantage of. Carbon makes it pretty easy. Let’s imagine we have two cars. One was built in 1988 and the other was built in 2013. How can we check the difference between these two. Let’s see.

Now just like everything else in Carbon, you have many more methods available to you.
date differences

Have a play and see what you can come up with.


Modifying Dates and Times with Carbon

When we talk about Modifiers, we’re looking at methods such as startOfDay(), startOfDecade(), startOfMonth(), startOfWeek(), startOfYear(), and their associated methods of endOfDay(), endOfDecade(), endOfMonth(), endOfWeek(), and endOfYear(). Should you have a need for it, there is also a startOfCentury() and endOfCentury() for you to work with. We can check out these examples.

Carbon Next

The next() method is a really useful one in Carbon. How often do you talk to other people using the next nomenclature? You’ll be like, “Hey Tom, I’ll see you next week!” or “Jill, I don’t have a free night until next Wednesday” and so on and so forth. The next() method in Carbon accepts a dayOfWeek integer value, however it is null by default. Recall that in PHP 0 is Sunday, and 6 is Saturday. Let’s try it out.

If we omit the argument to the next() method, it will just move forward one week starting from today. Today is Thursday as we write this, so this is what the output is when we combine with our handy toCookieString() formatting method.

Carbon Previous

The complimentary method to next() is of course previous(). Let’s try it.


Carbon Copy

The copy() method is very important in Carbon. The reason is, if you call modifying methods on an instance of Carbon, that instance gets immediately updated directly. It is not a copy of the object, but a reference. Let’s see an example.

This works as expected. We create a Carbon instance based on a Thursday, add a day, and see that the output is now Friday. Check this out however.

This is saying that $carbonone and $carbontwo are equal, is that right? It looks like $carbonone should be a Thursday and $carbontwo should be a Friday, why is this saying the days are equal? Let’s add in the copy() method to get something more consistent.

This behavior is a little more consistent with what we might expect. In the first example, all we are doing is taking the original instance, adding a day, then assigning that to a new variable. The original variable holding the Carbon instance is also updated however, much like you would expect with a reference or pointer type of situation.

The second example uses the copy() method to clone the object, so that we can leave the original Carbon instance untouched. This way when you add fluent or chained calls onto the end of a Carbon instance which includes copy() within the chain, you can leave the original in tact. I hope that makes sense. Let’s see one more example to drive it home.

This does not work correctly

Adding the copy() method makes things work correctly


Carbon in the Real World

So you might be a little overwhelmed with the sheer number of ways you can interact with, update, modify, and otherwise hack dates and times using the Carbon Library. I know this, because that is exactly what I am thinking! In all seriousness however, the best way to see how Carbon is used in the real world is to look at projects that actually use Carbon. The best example we could look at is Laravel Cashier, which makes heavy use of Carbon. Let’s see how.

Checking for a Trial period

We can see use of the today() method (instantiation) and lt() method (comparison).

Checking for a Grace Period

We can see use of the now() method (instantiation) and lt() method (comparison), as well as the instance() method (instantiation).

Creating a Carbon Instance from a Timestamp

Here we can see the code making use of the createFromTimestamp() method and setTimeZone() method which is fluent.

Calculating Remaining Trial Days

This gives us a good idea of how Carbon might be used in the real world with real code powering real transactions. Read through the source further on your own if you are interested!


Easy PHP Dates and Times With Carbon Summary

Like most lengthy tutorials, we are coming away from this with more knowledge about the topic than we began with. After testing all of these various methods for yourself in your own sandbox, you will come up with ideas on how to best implement Carbon in your own projects. In addition, we were able to examine Carbon usage in a real world project by way of the popular Laravel Cashier package.