【问题标题】:Why I'm not geting proper date comparison result in following situation?为什么在以下情况下我没有得到正确的日期比较结果?
【发布时间】:2013-12-20 07:04:55
【问题描述】:

我的代码如下:

if(!empty($form_data["birth_date"])){
          $date1   = date('d/m/y');

          $tempArr = explode('/', $form_data["birth_date"]);
          $date2   = date("d/m/y", mktime(0, 0, 0, $tempArr[1] ,$tempArr[0], $tempArr[2]));

        }

if(strtotime($date2) >= strtotime($date1)) 
          echo "Please enter date which is not greater than today's date!!!";

即使输入的日期小于今天的日期,我也会收到错误消息。我正在使用 dd/mm/yyyy 格式。任何人都可以帮助我吗?提前致谢。

$date1 = 20/12/2013;

$date2 = 21/03/1985;

【问题讨论】:

  • 你能显示值吗,你正在检查?
  • 看看你在两个日期的值上得到了什么
  • @DainisAbols:我已将要比较的值(在转换为时间戳之前)添加到问题中。
  • $form_data["birth_date"] 输入是什么?
  • @DainisAbols:$date2 的值

标签: php date unix-timestamp strtotime date-comparison


【解决方案1】:

strtotime 函数用于日期格式 YYYY/MM/DD 所以请转换日期这个格式然后应用 strtotime() 并比较两个日期后

【讨论】:

  • Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
【解决方案2】:

为此使用 DateTime 函数。试试这样:

$date1 = new DateTime("now");
$date2 = new DateTime("12/12/2013 21:00:02");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);

输出:

bool(false)
bool(true)
bool(false)

【讨论】:

  • 但我不想像您在代码第二行中那样将时间作为参数发送。
  • 您不能在strtotime()new DateTime() 中使用d/m/Y 格式,因为它不是有效的标准格式; php parse 假设它是m/d/Y,这就是为什么当你尝试输入大于 12 的天时会出现错误,比如21/12/2013
猜你喜欢
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 2020-09-23
  • 2012-10-30
相关资源
最近更新 更多