Skip to content
PHP Logo

What are the potential pitfalls of using string functions like substr() to extract day, month, and year from a date input in PHP?

Using string functions like substr() to extract day, month, and year from a date input in PHP can be error-prone if the date format changes or if the input is not consistent. It is better to use PHP's built-in DateTime class to parse and extract date components reliably.

php
$dateInput = "2022-12-31";
$date = new DateTime($dateInput);
$day = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');

echo "Day: $day, Month: $month, Year: $year";