繁体   English   中英

如何从日期获取年份和月份-PHP

[英]How to get year and month from a date - PHP

如何从给定日期获取年份和月份。

例如$dateValue = '2012-01-05';

从这个日期起,我需要将2012年1月作为月份

使用strtotime()

$time=strtotime($dateValue);
$month=date("F",$time);
$year=date("Y",$time);

使用文档中的date()strtotime()

$date = "2012-01-05";

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

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

echo $month

可能不是最有效的代码,但是在这里:

$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

我正在使用这些功能来获取日期的年,月,日

你应该把它们放在课堂上

    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");
    }

我将分享我的代码:

在给定的示例日期中:

$dateValue = '2012-01-05';

它会像这样:

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;
    }

并返回值: 2012年1月5日-星期四

您可以使用以下代码:

$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);
$dateValue = '2012-01-05';
$yeararray = explode("-", $dateValue);

echo "Year : ". $yeararray[0];
echo "Month : ". date( 'F', mktime(0, 0, 0, $yeararray[1]));

Usiong explode()可以做到。

$dateValue = '2012-01-05';
$year = date('Y',strtotime($dateValue));
$month = date('F',strtotime($dateValue));

我个人更喜欢使用此快捷方式。 输出仍然是相同的,但是您不需要将月份和年份存储在单独的变量中

$dateValue = '2012-01-05';
$formattedValue = date("F Y", strtotime($dateValue));
echo $formattedValue; //Output should be January 2012

关于使用此技巧的一点说明,您可以使用逗号分隔月份和年份,如下所示:

$formattedValue = date("F, Y", strtotime($dateValue));
echo $formattedValue //Output should be January, 2012
$dateValue = strtotime($q);

$yr = date("Y", $dateValue) ." "; 
$mon = date("m", $dateValue)." "; 
$date = date("d", $dateValue); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM