英文:
PHP compare dates returns true
问题
我有一个来自日期数组的日期如下:
$expiryDate = date('d F Y', max($expiryDates));
echo $expiryDate . ' < ' . date('d F Y'); // 输出: 01 January 2021 < 06 January 2020
我试图比较这个日期是否小于今天的日期,但它返回 true?
if ($expiryDate < date('d F Y')) {
// 做一些事情
}
2021年1月1日显然比2020年1月6日大,为什么它返回 true?
英文:
I have the following date from a dates array:
$expiryDate = date('d F Y', max($expiryDates));
echo $expiryDate . ' < ' . date('d F Y'); // outputs: 01 January 2021 < 06 January 2020
I'm trying to compare if this date is less than todays date but its returning true?
if ($expiryDate < date('d F Y') {
// do something
}
01 January 2021 is clearly greater than 06 January 2020 so why is it returning true
答案1
得分: 1
如果两个日期的日期格式不同,您可以使用strtotime函数来比较这两个日期。
$d1 = "10-08-16";
$d2 = "2011-11-20";
$dn1 = strtotime($d1);
$dn2 = strtotime($d2);
if ($dn1 > $dn2)
echo "$dn1 晚于 $dn2";
else
echo "$dn1 早于 $dn2";
注意:上述代码片段是用PHP编写的,用于比较两个日期的先后顺序。
英文:
If the date formats for both your dates are different you can use, strtotime to compare both dates.
$d1 = "10-08-16";
$d2 = "2011-11-20";
$dn1 = strtotime($d1);
$dn2 = strtotime($d2);
if ($dn1 > $dn2)
echo "$dn1 is latest than $dn2";
else
echo "$dn1 is older than $dn2";
?>
答案2
得分: 1
你正在比较字符串,这就是问题所在。
你可以使用 DateTime
类来实现你想要的功能。
$now = new DateTime();
$yesterday = new DateTime('yesterday');
# 这将返回 1,表示为真
echo $now > $yesterday;
你可以在 https://www.php.net/manual/en/datetime.examples-arithmetic.php 中找到更多示例。
英文:
You are comparing strings, thats the problem.
You can use DateTime
class to do what you want.
$now = new DateTime();
$yesterday = new DateTime('yesterday');
# It will return 1 that is true
echo $now > $yesterday;
You can find more examples in https://www.php.net/manual/en/datetime.examples-arithmetic.php
答案3
得分: 1
你可以使用strtotime来比较日期。
$expiryDate = "01 January 2021";
if (strtotime($expiryDate) < strtotime(date('d F Y'))) {
echo "expiry date is less than current date";
} else {
echo "expiry date is greater than current date";
}
英文:
you can use strtotime to compare the dates
$expiryDate = "01 January 2021";
if (strtotime($expiryDate) < strtotime(date('d F Y'))) {
echo "expiry date is less than current date";
}else
echo "expiry date is greater than current date";
答案4
得分: 0
你必须使用正确的比较格式,并使用以下比较格式。
$expiryDate = date("Y-m-d H:i:s", max($expiryDates));
if ($expiryDate < date("Y-m-d H:i:s")) {
// 做一些操作
}
英文:
You have to use correct format for comparison and use below comparison format.
$expiryDate = date("Y-m-d H:i:s", max($expiryDates));
if ($expiryDate < date("Y-m-d H:i:s") {
// do something
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论