在比较日期和今天日期的代码中有什么问题? [英] What's the issue in a code written for comparing the date with today's date?

查看:161
本文介绍了在比较日期和今天日期的代码中有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要比较日期与当前日期(即今天的日期)。预计错误应该仅在要比较的日期大于今天日期时发生。它不应来自日期,小于或等于今天的日期。

I'm comparing a date with current date(i.e. today's date). It is expected that the error should come only when the date to be compared is greater than today's date. It should not come for date which is less than or equal to today's date.

我写了以下代码。

$submission_date = $_POST['submission_date']; //The date in mm-dd-yyyy format that is to be tested against today's date. The value in $submission date is 12-25-2014 
//This is a future date. Today's date is 12-10-2014 in dd-mm-yyyy format

$current_date = date('m-d-Y');

if (strtotime($submission_date) > strtotime($current_date))
{
   echo "Future date not accepted";
}

使用上面的代码我不会在以后的日期得到错误,

With the above code I'm not getting errors for future dates, sometimes I'm getting error for previous dates as well.

如何优化并使此代码正确和标准?

How to optimize and make this code correct and standard?

推荐答案

如果发布的格式是 mdY ,那么你不能直接使用 strtotime 函数,因为它将返回 false

If posted format is in m-d-Y, then you cannot convert it to unix timestamp directly with strtotime() function, because it will return false.

如果您需要使用 strtotime(),则通过简单将输入格式更改为 m / d / Y str_replace()

If you need to use strtotime() then change the input format to m/d/Y by simple str_replace().

另一方面,您可以使用 DateTime 类,您可以直接比较对象:

On the other hand, you could use DateTime class, where you can directly compare objects:

$submission_date = DateTime::createFromFormat('!m-d-Y', $submission_date);
$today_date = new DateTime('today');

if ($submission_date > $today_date) {
    echo "submission_date is in the future\n";
}

demo

如果您需要从DateTime对象中提取一些信息,使用 format() 方法,它接受与 date() 函数:

If you need to extract some information from DateTime objects, use format() method on them, which accepts same format as date() function:

echo $today_date->format('m/d/Y'); # 12/11/2014
echo $today_date->format('m-d-Y'); # 12-11-2014
echo $today_date->format('Y-m-d'); # 2014-12-11
echo $today_date->format('Y-Y-Y'); # 2014-2014-2014

演示

这篇关于在比较日期和今天日期的代码中有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆