What is the difference between using substr() and DateTime for extracting the year from a date value in PHP?
When extracting the year from a date value in PHP, using substr() involves manually manipulating the date string to extract the year, which can be error-prone and less efficient. On the other hand, using DateTime provides a more reliable and convenient way to extract the year from a date value, as it allows for easy manipulation and formatting of dates.
// Using substr() to extract the year from a date value
$date = '2022-10-15';
$year = substr($date, 0, 4);
echo $year;
// Using DateTime to extract the year from a date value
$date = '2022-10-15';
$dateTime = new DateTime($date);
$year = $dateTime->format('Y');
echo $year;