【问题标题】:Why is my date comparison function throwing errors? [duplicate]为什么我的日期比较函数会抛出错误? [复制]
【发布时间】:2015-02-13 13:37:54
【问题描述】:

我有一个 if 语句,它将输入日期与系统日期进行比较。

$Date > date('m/d/Y')

问题是当我输入12/16/2012时会抛出日期大于今天日期的错误。我不知道我的 if 语句中的问题是什么。我在该函数中有一个trycatch,可以捕获任何 InputException。

【问题讨论】:

  • 您在比较字符串,而不是日期
  • 在比较日期时尝试使用 strtotime
  • date_diff( date_create($Date), time());

标签: javascript php jquery


【解决方案1】:

比较字符串不会给你想要的输出。您可以使用strtotime 来比较日期,如下所示: strtotime($date) > date('m/d/Y',time())

【讨论】:

  • 您将数字 (strtotime()) 与字符串 (date()) 进行比较。
【解决方案2】:
strtotime($date) > strtotime(date('m/d/Y'));

【讨论】:

  • 为什么使用date()格式化当前时间,然后使用strtotime()解析格式化字符串?
【解决方案3】:

使用strtotime() 解析您存储在$Date 中的值以获取时间戳(即自1970 年1 月1 日以来经过的秒数)。然后将其与使用函数time()检索的当前时间戳进行比较

if (strototime($Date) > time()) {
    echo($Date.' is in the future.');
} else {
    echo($Date.' is in the past.');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2017-06-30
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多