How to Get the Current Year with PHP

Here, you will find comprehensive information about one of the most common issues in PHP: how to get the current year.

Below you can find the main functions, allowing you to do that with PHP.

Watch a course Learn object oriented PHP

Applying the date Function

To get the current year with PHP date function, it is necessary to pass in the Y format as follows:

<?php

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

?>

This example prints out current year’s full four-digit representation.

For getting a two-digit format, apply the lowercase y format character, like so:

<?php

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

?>

Applying the DateTime Object

In this section, you will find a more object-oriented approach, using the DateTime object as follows:

<?php

//apply DateTime.
$currentDate = new DateTime();
//Get the year by using the format method.
$year = $currentDate->format("Y");
//Printing that out
echo $year;

?>

So, the DateTime object is generated, and you can retrieve the current year via passing the Y character as a $format parameter.

For getting a two-digit format, using the y lowercase character is necessary.

Here is how to do it:

<?php

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

?>