How to Get the Current Year with PHP
On this page, you will get solutions to a common issue in PHP: how to get the current year.
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.
Applying the date Function
To get the current year with PHP date function, it is necessary to pass in the Y format as follows:
date function php
<?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:
get current date php
<?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:
get current year php
<?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 <kbd class="highlighted">$format </kbd> parameter.
For getting a two-digit format, using the y lowercase character is necessary.
Here is how to do it:
get 2-digit format current year
<?php
//Receiving the two-digit format of
//the current year withDateTime
$currentDate = new DateTime();
$year = $currentDate->format("y");
echo $year;
?>