php - 从日期字符串中获取年份

标签 php html

我想检查当前年份是否大于日期字符串(D-M-Y)这里是我的代码

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

最佳答案

您可以使用 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

关于php - 从日期字符串中获取年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12622331/

相关文章:

html - 较小的 div 内的中心 img 无法按预期工作

html - 将 CSS 类应用于同一标签的插件生成元素?

javascript - 单击单选按钮时如何启用文本字段

html - 如何在所有页面中使用相同的模态代码?

php - 从服务器编码的 JSON 数据出现问题,无法绘制图表

php - 如何在php中输出MySQL EXPLAIN数据?

javascript - 样式化 javascript 函数 *显示/隐藏* CSS/HTML/JS

javascript - 数据表+服务器端处理+搜索过滤

php - Laravel Eloquent : How to store model values before saving?

php - PDO 获取 Bcrypted 密码?