How to Extract Day, Month and Year in PHP ?
Last Updated :
02 Jan, 2024
Given a Date, the task is to extract day, month, and year from the date using PHP. There are various methods to extract day, month, and year, these are:
Approach 1: Using date() Function
The date() function in PHP allows you to format a date string. You can use it to extract the day, month, and year components.
PHP
<?php
$date = date ( '2024-01-01' );
$day = date ( 'd' , strtotime ( $date ));
$month = date ( 'm' , strtotime ( $date ));
$year = date ( 'Y' , strtotime ( $date ));
echo "Day: $day, Month: $month, Year: $year" ;
?>
|
Output
Day: 01, Month: 01, Year: 2024
Approach 2: Using DateTime Class
The DateTime class provides an object-oriented way to work with dates and times in PHP. You can use it to extract the day, month, and year components.
PHP
<?php
$date = new DateTime();
$day = $date ->format( 'd' );
$month = $date ->format( 'm' );
$year = $date ->format( 'Y' );
echo "Day: $day, Month: $month, Year: $year" ;
?>
|
Output
Day: 01, Month: 01, Year: 2024
Approach 3: Using getdate() Function
The getdate() function returns an associative array containing information about a given timestamp. You can use it to extract the day, month, and year components.
PHP
<?php
$date = getdate ();
$day = $date [ 'mday' ];
$month = $date [ 'mon' ];
$year = $date [ 'year' ];
echo "Day: $day, Month: $month, Year: $year" ;
?>
|
Output
Day: 1, Month: 1, Year: 2024
Share your thoughts in the comments
Please Login to comment...