Getting the current year using PHP.

In this beginner’s tutorial, I will show you how to get the current year using PHP. There are various ways to do this, so I will include a number of examples.

Getting the current year using PHP’s date function.

To get the current year using PHP’s date function, you can pass in the “Y” format character like so:

The example above will print out the full 4-digit representation of the current year.

If you only want to retrieve the 2-digit format, then you can use the lowercase “y” format character:

The snippet above will print out 20 instead of 2020, or 19 instead of 2019, etc.

Using the DateTime object.

If you wish to use a more object-orientated approach, then you can use PHP’s DateTime object:

Here, we created a DateTime object and then retrieved the current year by passing the “Y” character in as the $format parameter.

To get the 2-digit format instead, you can use the lowercase “y” character:

As you can see, both the date function and the DateTime object use the exact same format characters in this case.

Hopefully, you found this guide helpful!

Related articles:

Facebook Comments