How to Get the Current Year with PHP

  1. Applying the date Function
  2. Applying the DateTime Object

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.

A .Applying the date Function

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

1 //Get the current year with
2 //PHP's date function.
3 $year = date("Y");
4 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:

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

B.Applying the DateTime Object

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

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

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

Do you find this helpful?

Related articles