Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get year and month from a date - PHP

Tags:

date

php

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.

like image 254
Sara Avatar asked Jan 23 '12 06:01

Sara


6 Answers

Use strtotime():

$time=strtotime($dateValue);
$month=date("F",$time);
$year=date("Y",$time);
like image 52
Tim Withers Avatar answered Nov 15 '22 11:11

Tim Withers


Using date() and strtotime() from the docs.

$date = "2012-01-05";

$year = date('Y', strtotime($date));

$month = date('F', strtotime($date));

echo $month
like image 37
Mob Avatar answered Nov 15 '22 09:11

Mob


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
like image 6
ariestav Avatar answered Nov 15 '22 09:11

ariestav


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");
    }
like image 6
Hiba Avatar answered Nov 15 '22 09:11

Hiba


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);
like image 5
anubhava Avatar answered Nov 15 '22 11:11

anubhava


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

like image 5
Mr.Unknown Avatar answered Nov 15 '22 09:11

Mr.Unknown