How to get year and month from a date - PHP

后端 未结 10 1325
一个人的身影
一个人的身影 2020-12-24 06:37

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

相关标签:
10条回答
  • 2020-12-24 07:27

    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");
        }
    
    0 讨论(0)
  • 2020-12-24 07:33
    $dateValue = '2012-01-05';
    $year = date('Y',strtotime($dateValue));
    $month = date('F',strtotime($dateValue));
    
    0 讨论(0)
  • 2020-12-24 07:37

    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);
    
    0 讨论(0)
  • 2020-12-24 07:39

    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
    
    0 讨论(0)
提交回复
热议问题