问题描述
我一直在努力设定一个特定的日期,但我没有正确地提出意见.我想从用户那里获取日期,并将该日期与今天的15天之前的日期进行比较.如果已超过15天,则转换为今天,否则打印出来.
i am struggling for a long time to set a specific date but i am not getting correct out put.i want to get date from user and compare that date with the date 15 days older then today. if it is older than 15 days then convert to today else print what it is.
$todaydate= $_GET['date'];// getting date as 201013 ddmmyy submitted by user
$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate);
$today =date("dmy"); //today ddmmyy
$older= date("dmy",strtotime("-15 day")); // before 15 days 051013
if ($todaydate <= $older){
$todaydate= $today;}
问题是,它以日期为数字并给出错误的结果.
problem is, it is taking date as number and giving wrong result.
推荐答案
比较日期字符串有点hacky,容易失败.尝试比较实际的日期对象
Comparing date strings is a bit hacky and prone to failure. Try comparing actual date objects
$userDate = DateTime::createFromFormat('dmy', $_GET['date']);
if ($userDate === false) {
throw new InvalidArgumentException('Invalid date string');
}
$cmp = new DateTime('15 days ago');
if ($userDate <= $cmp) {
$userDate = new DateTime();
}
此外, strtotime
有一些严格的限制(请参见 http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand ),在非美国语言环境中无效. DateTime
类更加灵活和最新.
Also, strtotime
has some severe limitations (see http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand) and is not useful in non-US locales. The DateTime
class is much more flexible and up-to-date.
这篇关于PHP日期比较早于15天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!