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 and month as January.
Use strtotime()
:
$time=strtotime($dateValue);
$month=date("F",$time);
$year=date("Y",$time);
Using date()
and strtotime()
from the docs.
$date = "2012-01-05";
$year = date('Y', strtotime($date));
$month = date('F', strtotime($date));
echo $month
Probably not the most efficient code, but here it goes:
$dateElements = explode('-', $dateValue);
$year = $dateElements[0];
echo $year; //2012
switch ($dateElements[1]) {
case '01' : $mo = "January";
break;
case '02' : $mo = "February";
break;
case '03' : $mo = "March";
break;
.
.
.
case '12' : $mo = "December";
break;
}
echo $mo; //January
I'm using these function to get year, month, day from the date
you should put them in a class
public function getYear($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("Y");
}
public function getMonth($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("m");
}
public function getDay($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("d");
}
You can use this code:
$dateValue = strtotime('2012-06-05');
$year = date('Y',$dateValue);
$monthName = date('F',$dateValue);
$monthNo = date('m',$dateValue);
printf("m=[%s], m=[%d], y=[%s]\n", $monthName, $monthNo, $year);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With