Skip to content
PHP Logo

How can PHP developers efficiently extract and store date segments like days, months, and years from a given date string?

When extracting date segments like days, months, and years from a given date string in PHP, developers can utilize the DateTime class to easily parse the date and extract the desired segments using the format() method. By specifying the format characters 'd', 'm', and 'Y' for day, month, and year respectively, developers can efficiently extract and store these date segments for further processing.

php
$dateString = "2022-09-15";
$date = new DateTime($dateString);

$day = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');

echo "Day: " . $day . "\n";
echo "Month: " . $month . "\n";
echo "Year: " . $year . "\n";