Horje
How to Extract Day, Month and Year in PHP ?

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
  
// Get the current date
$date = date('2024-01-01');
  
// Extract day, month, and year
$day = date('d', strtotime($date));
$month = date('m', strtotime($date));
$year = date('Y', strtotime($date));
  
// Display the results
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
  
// Get the current date
$date = new DateTime();
  
// Extract day, month, and year
$day = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');
  
// Display the results
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
  
// Get the current date
$date = getdate();
  
// Extract day, month, and year
$day = $date['mday'];
$month = $date['mon'];
$year = $date['year'];
  
// Display the results
echo "Day: $day, Month: $month, Year: $year";
  
?>

Output

Day: 1, Month: 1, Year: 2024



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How to use Modulo Operator in PHP ? How to use Modulo Operator in PHP ?
PHP Program to Check if a String Contains Uppercase, Lowercase, Special Characters and Numeric Values PHP Program to Check if a String Contains Uppercase, Lowercase, Special Characters and Numeric Values
How to Access Child Method From the Parent in VueJS ? How to Access Child Method From the Parent in VueJS ?
How to Set Max and Min Value for Y Axis in Chart.js ? How to Set Max and Min Value for Y Axis in Chart.js ?
Asia Cup Country Wise Winners List (1984-2023) Asia Cup Country Wise Winners List (1984-2023)

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12