How to get year and month from a given date.
e.g. $dateValue = \'2012-01-05\';
From this date I need to get year as 2012
I personally prefer using this shortcut. The output will still be the same, but you don't need to store the month and year in separate variables
$dateValue = '2012-01-05';
$formattedValue = date("F Y", strtotime($dateValue));
echo $formattedValue; //Output should be January 2012
A little side note on using this trick, you can use comma's to separate the month and year like so:
$formattedValue = date("F, Y", strtotime($dateValue));
echo $formattedValue //Output should be January, 2012
Use strtotime():
$time=strtotime($dateValue);
$month=date("F",$time);
$year=date("Y",$time);
I will share my code:
In your given example date:
$dateValue = '2012-01-05';
It will go like this:
dateName($dateValue);
function dateName($date) {
$result = "";
$convert_date = strtotime($date);
$month = date('F',$convert_date);
$year = date('Y',$convert_date);
$name_day = date('l',$convert_date);
$day = date('j',$convert_date);
$result = $month . " " . $day . ", " . $year . " - " . $name_day;
return $result;
}
and will return a value: January 5, 2012 - Thursday
$dateValue = '2012-01-05';
$yeararray = explode("-", $dateValue);
echo "Year : ". $yeararray[0];
echo "Month : ". date( 'F', mktime(0, 0, 0, $yeararray[1]));
Usiong explode() this can be done.
$dateValue = strtotime($q);
$yr = date("Y", $dateValue) ." ";
$mon = date("m", $dateValue)." ";
$date = date("d", $dateValue);
Using date() and strtotime() from the docs.
$date = "2012-01-05";
$year = date('Y', strtotime($date));
$month = date('F', strtotime($date));
echo $month