PHP';s使用date()无法进行时间和日期比较


PHP's time and date comparison not working using date()

我想将验证规则添加到我的输入表单中,这样人们就不能选择比今天更高的日期,但由于某些原因,我的操作员无法正常工作。。。至少我不认为他们是

//plain use of comparison operators
$a = 4; $b = 4;
if($a <= $b) { echo "umm?"; } // this return true
date_default_timezone_set('Europe/Copenhagen');
$timezone = date_default_timezone_get();
$today = date("d/m/y");
if(!empty($date['dateA']) && (date($date['dateA']) <= $today)) {

现在最后一个if语句正在以与$date数组格式相同的格式获取$today值。

这是让我发疯的原因。。。if:

$today = 08/02/2015

$date = 07/02/2015返回true$date = 08/02/2015返回false为什么不返回true

当我使用<=来确保$date不能高于$today时,为什么$date <= $today在它们具有相同值时不返回true?据我所知,它的作用或多或少像$date < $today

此外,我曾尝试使用strtotime而不是$date的日期,但它的作用仍然相同。。。。

那该怎么办呢?

我不知道为什么要坚持字符串比较。我建议对数学数字使用数学运算。

这样做:

if(strtotime($date) < time())
{
   // then allow doing something
}

strtotime()将已有的日期字符串(例如:"22/5/2014")转换为整数时间戳。time()还返回今天的时间戳。然后,您可以使用这两个数字进行操作。

虽然上面的方法完全有效,但您也可以在PHP中使用日期对象,它非常精确,可以隐式计算闰年等。

PHP文档示例:

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

点击此处阅读更多:http://php.net/manual/en/datetime.diff.php

当前它首先检查一个较低的日期,而应该首先检查年份,因为字符串比较从左到右一次检查一个字符。

你可以将日期格式存储在年/月/日来解决这个问题,但这样做有点难看。

我建议使用时间戳,这是自1970年1月1日00:00:00 GMT以来的秒数,可以通过调用time()在PHP中检索,该函数提供当前时间戳。您可以通过调用strtotime()来检索某个日期的时间戳。

您目前正在使用字符串比较,这不是比较日期的推荐方法。尽管如此,我不知道为什么相等性检查失败,但我认为您应该使用DateTime对象:http://php.net/manual/en/class.datetime.php(仅当您使用PHP>=5.2.2时,因为PHP手册说DateTime比较在以前的版本中无法正常工作)

在您的情况下,最后一行将变为:if(!empty($date['dateA']) && DateTime::createFromFormat('d/m/Y', $date['dateA']) <= DateTime::createFromFormat('d/m/Y', $today))