How to get the current year using PHP.

In this tutorial, we will show you how to get the current year using PHP.

There are a number of different ways to do this, so we will include a few examples.

Get 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:

//Getting the current year using
//PHP's date function.
$year = date("Y");
echo $year;

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 instead:

$year = date("y");
echo $year;

The snippet above will print out 22 instead of 2022, or 19 instead of 2019, etc.

Using the DateTime object.

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

//Getting the current year
//using DateTime.
$currentDate = new DateTime();
//Get the year by using the format method.
$year = $currentDate->format("Y");
//Print it out
echo $year;

Here, we created a DateTime object.

We 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:

//Getting the two-digit format of
//the current year using DateTime
$currentDate = new DateTime();
$year = $currentDate->format("y");
echo $year;

As you can see, both the date function and the DateTime object use the exact same “format characters”.

Related articles: