php 如何仅获取日期字符串的年份部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6433482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:22:31  来源:igfitidea点击:

How to get only the year part of a date string?

phpdate

提问by daniel__

I have an input date by user like this: 1979-06-13

我有这样的用户输入日期: 1979-06-13

Now, i want to compare the year:

现在,我想比较一下年份:

foreach ($list as $key) {
    $year = 1979;
    if ($key > $year) { //only the year
        echo (error);
        }
}

How can I get only the year?

我怎么能只得到年份?

Thanks

谢谢

回答by bmb

Probably more expensive, but possibly more flexible, use strtotime() to convert to a timestamp and date() to extract the part of the date you want.

可能更昂贵,但可能更灵活,使用 strtotime() 转换为时间戳和 date() 以提取您想要的日期部分。

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

回答by Felix Kling

With strtok:

strtok

$year = strtok($date, '-');

If you want the year as integer, you can also use intval:

如果您希望年份为整数,您还可以使用intval

$year = intval($date);

回答by aimme

Heres an easy and exact way.

这是一个简单而准确的方法。

//suppose
$dateProvided="1979-06-13";
//get first 4 characters only
$yearOnly=substr($dateProvided,0,4);
echo $yearOnly;
//1979

and one more thing to know, in some cases like, for example when the date is like 2010-00-00 the date function don't work as expected, it would return 2009 instead of 2010. heres an example

还有一件事要知道,在某些情况下,例如,当日期类似于 2010-00-00 时,日期函数不能按预期工作,它将返回 2009 而不是 2010。这是一个例子

//suppose
$dateProvided="2010-00-00";
$yearOnly = date('Y', strtotime($dateProvided));
//we expect year to be 2010 but the value of year would be 2009
echo $yearOnly;
//2009

回答by thescientist

you could explode the date.

你可以爆炸日期。

$inputDate = "1979-06-13";
$myDate = 1979;
$datePieces = explode("-",$inputDate);
if (intval($datePieces[0]) > $myDate){
  echo "error";
};

http://php.net/manual/en/function.explode.php

http://php.net/manual/en/function.explode.php