How to get year and month from a date - PHP

后端 未结 10 1324
一个人的身影
一个人的身影 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:15

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

    Use strtotime():

    $time=strtotime($dateValue);
    $month=date("F",$time);
    $year=date("Y",$time);
    
    0 讨论(0)
  • 2020-12-24 07:18

    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

    0 讨论(0)
  • 2020-12-24 07:21
    $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.

    0 讨论(0)
  • 2020-12-24 07:24
    $dateValue = strtotime($q);
    
    $yr = date("Y", $dateValue) ." "; 
    $mon = date("m", $dateValue)." "; 
    $date = date("d", $dateValue); 
    
    0 讨论(0)
  • 2020-12-24 07:26

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

    $date = "2012-01-05";
    
    $year = date('Y', strtotime($date));
    
    $month = date('F', strtotime($date));
    
    echo $month
    
    0 讨论(0)
提交回复
热议问题