gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:09:12 25 4
gpt4 key购买 nike

我想检查当前年份是否大于日期字符串(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com