Calculate the Century in PHP

In this example we are going to see how given a year we can calculate the century in PHP. To do this we will see what different alternatives we have within PHP.

Century in PHP using date methods

If we look in the documentation at PHP about whether there is a method that gives us this in the language, we can reach the method strftime(), which has a format that returns the century. Specifically the format %C.

So if we write the following code we will obtain, given a year, the century in PHP:

echo strftime("%C");

The “problem” you have strftime() is that it handles dates based on UNIX milliseconds. That is why in some operating systems we are surprised that there is no support for negative milliseconds and therefore we do not see dates before 1970. And therefore we could not calculate the century in PHP from dates before this.

It seems that other date management functions like date() or the DateTime object does not give us anything to calculate the century in PHP.

Century in PHP manipulating the date as a string

So we changed strategy and looked for a way to obtain the century from the first two figures of the year. Since the century is nothing more than adding one to those first two figures.

To do this, the first thing we will do is check that the string is numeric. To do this we use the method is_numeric:

if (is_numeric($year))

In that case what we will have to do is convert the year to a four-character string, padding with zeros on the left if necessary. To do this we will rely on the function str_pad, which allows us to set a minimum size and padding.

Specifically we will do the following:

$year = str_pad($year,4,"0",STR_PAD_LEFT);

That is, fill up to 4 characters with zeros, from the left (STR_PAD_LEFT).

The next thing will be to take the first two digits and add one to be able to calculate the century in PHP. This step is simple and all we need to do is use the substr.

$century = substr($year,0,2)+1;

It is a manual method, but effective. In this way we have been able to calculate the century in PHP manipulating strings.

Leave a Comment