View Full Version : Extracting year from a date variable

04-15-2012, 11:37 PM
Hi Folks,

I have an array of date variables $Gv_end_date[]

I would like to extract the year into a separate variable but have hit a brick wall and am doing something quite wrong and no doubt stupid. I've put in a couple of echos with an exit and the output looks like the following. Any help pleasssse

$endyear = date(Y,$Gv_end_date[$i]);
echo $Gv_end_date[$i]; // displays 2015-07-22 (this is expected)
echo $endyear; // displays 1970

04-15-2012, 11:49 PM
You can either split the year out via substring or explode, or convert it into a datetime and extract the year. I'd use a datetime, so I'll use strtotime.

$date = strtotime($Gv_end_date[$i]);
$endyear = date('Y', $date);

DateTime class can be used instead, but it does take a 5.3+ version of PHP to use it.

04-15-2012, 11:57 PM
Thankyou Fou-Lu (can't believe it's that simple) very much appreciated.