从日期字符串中获取年份

Rak*_*esh 3 html php

我想检查当前年份是否大于日期字符串(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";
}
Run Code Online (Sandbox Code Playgroud)

h2o*_*ooo 7

您可以使用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";
}
Run Code Online (Sandbox Code Playgroud)

更新

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

$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";
}
Run Code Online (Sandbox Code Playgroud)

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