Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

php - What's the issue in a code written for comparing the date with today's date?

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.

I've written following code for it.

$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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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
";
}

demo

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

demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...