Jack Roscoe Jack Roscoe - 3 months ago 12
PHP Question

How to extract only 'Day' value from full 'Date' string?

I have an array of Date values in the format of

'Y-m-d'
. I want to loop over the array and only extract the day (
'd'
) of each member, but can't figure out to split it. Do I use substrings in some way?

Put simply, I have
'2010-11-24'
, and I want to get just
'24'
from that. The problem being the day could be either single or double figures.

Answer

If you have PHP < 5.3, use strtotime():

$string = "2010-11-24";
$timestamp = strtotime($string);
echo date("d", $timestamp);

If you have PHP >= 5.3, use a DateTime based solution using createFromFormat - DateTime is the future and can deal with dates beyond 1900 and 2038:

 $string = "2010-11-24";
 $date = DateTime::createFromFormat("Y-m-d", $string);
 echo $date->format("d");