Problem:
You want to get the current year. In the bottom of every website, there is a copyright notice which displays the current year. You might be looking for PHP code to display that year.
Solution:
To display current year is very easy and simple in PHP. You can use any one of the following method-
Method 1: Using date() function
Use the format character “Y”(Capital letter) in the date() function to display the current year. It will display 4 digits numeric year. See the following code-
<?php $year = date("Y"); echo "Current year is: " . $year; ?>
[wpdm_file id=127]
Output:
Current year is: 2014
Method 2: Using format() method of DateTime class from SPL
PHP provides some ready-made class(which is called standard PHP library, SPL in short) to solve common works. One of those classes is DateTIme class. Using format() method of this class, we can display current year. It takes two steps-
- Create a DateTime object
- Use format() method to format the date object and returns the current year.
See the following example-
<?php $dateObj = new DateTime; $year = $dateObj->format("Y"); echo "Current year is: " . $year; ?>
[wpdm_file id=128]
Output:
Current year is: 2014