Compare current date with a date in d/mm/yyyy format in PHP

六月ゝ 毕业季﹏ 提交于 2019-12-12 04:01:19

问题


What is the best way to check if a given date - a string d/mm/yyyy is a past? When I used strtotime(), it didn't work well, because of non-American notation. Of course I might deal with the dates as strings and compare substrings, but there has to be a better way.

if((strtotime('now')-strtotime($date)) > 86400) echo $date;

回答1:


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.

strtotime() manual

So a simple str_replace('/', '-', $date) should do the trick.




回答2:


strtotime('now') is a hideous abuse of the function. You should just use time() to get the EXACT SAME result with none of the strtotime overhead.

$thatTime = date_create_from_format('d/m/Y', $date)->getTimestamp();
if (time() - $thatTime > 86400) echo $date;

relevant docs for date_create_from_format()




回答3:


Well the obvious answer would be to reformat the string like this:

$parts = explode('/',$dateStr);
if ((time() - strtotime("$parts[2]-$parts[1]-$parts[0]")) > 86400) {
  // do stuff
}

EDIT

However, Marc B's answer is better, so do that.




回答4:


If you're running >PHP5, this would do the trick:

function in_past($date) {
    $date = explode("/", $date);
    $now = time();
    $date = strtotime($date[1]."/".$date[0]."/".$date[2]);
    return $date < $now;
}

used like:

$old_date = "23/01/1985";
if (in_past($old_date))
    echo 'so last season';
else 
    echo 'future';


来源:https://stackoverflow.com/questions/8387034/compare-current-date-with-a-date-in-d-mm-yyyy-format-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!