Get year from date php code example

Problem:

You have a date which consists of day, month, và year. You just want to lớn retrieve the year from that date.

Bạn đang xem: Get year from date php code example

Solution:

There are few ways you can retrieve year from a date. In the following you’ll see different ways to retrieve year from current date or from any date –

Method 1: Using only date() function to lớn get current year

PHP’s date() function can let you know date & time related information based on the formatting string it takes in its first parameter. It can take two parameters. If you use only one parameter, It will return info about the current time.

Xem thêm: Tạo Menu Dropdown Bằng Css Và Javascript, Thực Hành Xây Dựng Menu Dropdown

Depending on the formatting parameter you can get two types of output đầu ra as the year-

Y- A four digit numeric representation of a year. Ex. 2001y – A two digit numeric representation of a year. Ex. 01

Now, see these in kích hoạt in the example-

";echo "2 digit of current year is: " . Date("y");?>

Output:4 digit of current year is: 20142 digit of current year is: 14

Method 2: Using strtotime() & date() function lớn get year from any date

In this method, khổng lồ get the year, we’ll follow two steps-

We’ll use the date() function that we used in the method 1.

See how it works in action in the following example-

";echo "2 digit of current year is: " . Date("y", $timestamp);?>

Output:4 digit of current year is: 19932 digit of current year is: 93


*


In the above example,I used 5th February 1993 as date format. You may have different date format. Don’t worry. Any format will work as long as you follow the supported date & time formats

Method 3: Using DateTime class lớn get current year

From PHP 5.2, PHP provides some ready-made classes khổng lồ solve daily problems. One of the classes is DateTime which helps to solve date time related issues.

To get current year using DateTime class, we’ll follow two steps-

See the following example-

format("Y");echo "";echo "2 digit of current year is: " . $now->format("y");?>

Output:4 digit of current year is: 20142 digit of current year is: 14

Method 4: Using CreateFromFormat() method lớn get year from any date

In this method, we’ll retrieve year from any date in two steps-

Then, we’ll retrieve the year using format() method

See it in action in the following example –

format("Y");echo "";echo "2 digit of current year is: " . $dateObj->format("y");?>