Dates in PHP

Explanations and common practices for working with dates in PHP. We explore the ways of treating dates in the PHP language, in a simple and practical way, natively and through the Carbon library.

One of the most recurring tasks in the development of any application is working with dates. Of course, PHP is no exception.

The language natively offers us enough mechanisms to work with dates, but even so it may be a good idea to rely on some additional library, such as the well-known Carbon library. In this article we are going to show some examples of handling dates natively and we will also explain how improve the possibilities of working with dates and time using Carbona popular PHP library.

Dates in PHP natively

To work with dates in PHP you don’t really need to go to any kind of plugin, beyond the programming language itself. PHP has a class named DateTime which encompasses all the work necessary to process dates and perform calculations with datesas well as with hours.

The DateTime class is available as of PHP 5 and can be used in two different ways, through common functions and through the object-oriented paradigm. That is why we will see two work alternatives in this article.

build dates

Objects of the DateTime class can be constructed using the constructor of the date class.

$date = new DateTime(“2022-02-18”);

The supported input formats for the date can be diverse. Now we’ll even see how you can create your own custom formats. But it is important to know that if the indicated format is not admitted, an exception would be raised that we would need to deal with.

try { $date = new DateTime(“2022 02 18”); } catch(Exception $e) { echo ‘Date misconstructed: ‘ . $e->getMessage(); }

Exceptions are often awkward to deal with, so we may find it more useful to create dates by calling the “createFromFormat” method. This method allows us to deliver the check-in date in any other format we need.

$date = DateTime::createFromFormat(“Y md”, “2022 02 18”);

Build dates in PHP with functions

If we are misled, PHP also offers this API for working with dates using traditional functions.

See also  Write short titles

The same examples that we have seen before can be written in this other way.

Date Creation:

$date = date_create(“2022-02-18”);

Creation of the date from a custom format.

$date = date_create_from_format(“Y md”, “2022 02 18”);

Operate with dates in PHP

Once we have DateTime objects, we can perform operations on them to achieve whatever behaviors are needed.

The most typical would be to display the date with any desired format. To do this we use the format() method or the date_format() function, which is actually the same thing, depending on whether we prefer to work with the object directly or prefer the function style.

$date->format(‘d/m/Y’);

It would be equivalent to:

date_format($date, ‘d/m/Y’);

We will notice that the DateTime class has a set of methods to get operate with dates and do regular jobs, such as adding or subtracting days, weeks, or months, to a date.

For example, we add time intervals using the add() method. So we add a day to the date we had before.

$date->add(new DateInterval(‘P1D’));

This code would be equivalent:

$date->add(DateInterval::createFromDateString(‘1 day’));

You may agree with us that this code is not entirely intuitive. It would require some explanation and study to be able to understand it. For this reason it is very common that when we work with dates in PHP we end up using some extra library like the one we are going to see below.

Carbon library for working with dates in PHP

Carbon is one of those bookstores that once you get familiar with it you don’t want to go back to work without their help. Serves to make all kinds of treatments and calculations with dates and timesbut in a simple and intuitive way.

Perhaps you need to do complex things with dates, like calculating the number of days, minutes, and seconds between any two dates, or simple things like adding months or years to a date. For both cases, you may need to spend a lot of time reading the PHP documentation to get the correct method, or just googling for a solution already posted by another developer. However, if you know Carbon you will have it much easier.

See also  jQuery Handbook

Carbon has countless methods of creating a date and of course to operate with them.

For example, we can create the date of the current instant with:

$now = Carbon::now();

But if you want today’s date at 00:00:00, then you use:

$today = Carbon::today();

If it is yesterday’s date it would be:

$yesterday = Carbon::yesterday();

To create custom dates it is very convenient to use this other method:

$date = Carbon::createFromDate(2022, 2, 18);

You can even comfortably work with specific time zones:

$date = Carbon::createFromDate(2022, 2, 18, ‘Europe/Madrid’);

Of course, we can create a Carbon object using a completely custom input format.

Carbon::createFromFormat(‘Ym-d’, ‘2022-02-18’)

These are just a few examples so that we can see the variety of methods that we have available to generate dates.

Later, working with dates using Carbon is very simple. We simply have to start from a Carbon object created with any of its methods and make use of its various methods.

For example, we can add a number of days to a date like this:

$date->addDays(15);

Or subtract months like this:

$date->subMonths(2);

Another very useful example of Carbon is the ability to display the difference of one date from another in an easy-to-read format.

Carbon::now()->subDays(10)->diffForHumans();

This would return something like “10 days ago”. Of course, you will need to localize it into Spanish so that it tells you in our language, which is also very simple.

Carbon::now()->addDays(220)->locale(‘es_ES’);

How to use Carbon for date treatments

For To use the Carbon library you have to install it in your application via Composer. If you use a framework like Laravel or Symfony you won’t need to do this, but if your application is bareback PHP then you’ll have to install it by hand.

It’s not complicated and you can. Once you have installed Composer, you have to include Carbon as a dependency with this command:

See also  The hidden object

composer requires nesbot/carbon

Now that you have Carbon installed in your project, it’s a simple matter of requiring the composer autoload, as explained in the aforementioned Composer manual.

require ‘vendor/autoload.php’;

Next you have to use the Carbon namespace, with this PHP statement at the beginning of your file:

use Carbon\Carbon;

Using a facade to work with Carbon

To finish, I want to recommend that when you use Carbon you create your own class that is in charge of providing a simple interface for you to use the Carbon methods you need.

I generally have a personal Date class that has all the functions that I generally use, such as creating a date from a “MySQL date” field, or creating a date in Spanish format, English format, etc.

This allows you to centralize all your application’s dated work in a single file, which has several advantages:

  • It allows you to forget about the complications of date calculations in your entire application and call the methods that are easy for you. That is, you create a simplified interface for your use case of a large and sometimes complex library like Carbon.
  • If you later need to change Carbon with another library, you would only have to modify a single class, where you have centralized all the work with the date library, which reduces the potential maintenance of your application.

This recommendation is nothing more than a design pattern known as “facade”.

conclusion

In this article we have made a general analysis of the possibilities you have for the date handling in php. It is a broad subject, since there are thousands of possibilities in working with dates. Calculating with date is often a complex task, but with the help of libraries like Carbon everything is much easier.

In the next article in this manual we will see some common practical exercises in applications, such as . A good opportunity to continue learning and practicing the use of dates in PHP.

Loading Facebook Comments ...
Loading Disqus Comments ...