4

我想检查当前年份是否大于日期字符串(DMY)这是我的代码

$OldDate = "09-30-2011";
$OldYear = strtok($OldDate, '-');
$NewYear = date("Y");

if ($OldYear < $NewYear) {
    echo "Year is less than current year"   
} else {
    echo "Year is greater than current year";
}
4

6 回答 6

8

您可以使用strtotime()

$OldDate = "2011-09-30";

$oldDateUnix = strtotime($OldDate);
if(date("Y", $oldDateUnix) < date("Y")) {
    echo "Year is less than current year";
} else {
    echo "Year is greater than current year";
}

更新

因为您使用的是非常规的日期戳,所以您必须使用不同的方法,例如:

$OldDate = "09-30-2011";
list($month, $day, $year) = explode("-", $OldDate);
$oldDateUnix = strtotime($year . "-" . $month . "-" . $day);
if(date("Y", $oldDateUnix) < date("Y")) {
    echo "Year is less than current year";
} else {
    echo "Year is greater than current year";
}

注意:如果您想始终确保您的日期被 正确理解strtotime,请使用YYYY-MM-DD

于 2012-09-27T13:20:29.793 回答
1

使用日期函数获取年份

$OldDate = date("Y",strtotime("09-30-2011"));
$NewYear = date("Y",strtotime("now"));

if($OldYear<$NewYear)
{
echo "Year is less than current year"   
}
else
{
 echo "Year is greater than current year";
 }
于 2012-09-27T13:21:12.540 回答
1

您可以通过以下方式实现您的目标:

$input_date = date("09-30-2011");
$input_date_arr = explode("-", $input_date);
$currYear = date("Y");
$inputYear = $input_date_arr[2];

if ($currYear > $inputYear) {
echo "Current year is greater than given year!";
} else {
echo "Current year is not greater than given year!";
}
于 2020-02-12T06:53:17.120 回答
0
       $OldDate = "09-30-2011";
       $OldYear = date('Y',strtotime($OldDate));
       $NewYear = date("Y");
       if($OldYear<$NewYear)
        {
         echo "Year is less than current year"   
          }
        else
         {
          echo "Year is greater than current year";
         }
于 2012-09-27T13:21:27.330 回答
0

您可以将字符串转换为时间戳,并使用当前时间戳进行检查

if(time($OldDate) < time()){
// do stuff
} else {
// do other stuff
}
于 2012-09-27T13:26:07.530 回答
0

做这个,

$dateString = '2021-02-24';                     

$yr = date("Y", strtotime($dateString)); 
$mon = date("m", strtotime($dateString)); 
$date = date("d", strtotime($dateString)); 
于 2021-07-05T16:09:33.830 回答