我每年都有一个活动,从五月开始,到九月份结束。我如何重写这个以检查一个日期是否在一个月的范围内?
这是我的工作代码,但我必须每年手动更改。
$queryDate是由数据采集器设置的
<?php
$startDate = strtotime("05/01/20");
$endDate = strtotime("09/30/20");
$comparisonDate = $queryDate;
$comparisonDate = strtotime($comparisonDate);
if($startDate <= $comparisonDate && $comparisonDate <= $endDate)
{
echo 'OK';
}else{
echo 'NO';
}
?>已经找到了这个看似能够解决问题的小代码--但我不知道如何让它检查多个月或(d/m)。如果可能的话,在一个月内确定一个具体的日期,比如05/5月至9月25日(d/m)。
<?php
$date = "2019-11-30";
if(date("m", strtotime($date)) == date("11"))
{
echo 'ok';
}else{
echo 'no';
}
?>所有的线索或解决方案都受到高度赞赏。
问候
发布于 2019-12-28 09:51:47
您需要将此字符串转换为DateTime数据类型,这允许您进行任何进一步的比较:
$startDate = strtotime("05/01");
$endDate = strtotime("09/30");
$start1 = date('m/d', $startDate);
$end1 = date('m/d', $endDate);
$st_date = new DateTime($start1);
// echo $st_date->format('m/d/y').PHP_EOL;
$end_date = new DateTime($end1);
// echo $end_date->format('m/d/y').PHP_EOL;您的输入数据报警器字符串有其他日期时间掩码Y-m-d
$comparisonDate = "2020-06-30";
$comparisonDate = strtotime($comparisonDate);
$cmp1 = date('Y-m-d', $comparisonDate);
$cmp_date = new DateTime($cmp1);
$dtp_year = $cmp_date->format('y');
// echo $cmp_date->format('Y-m-d').PHP_EOL;在这里,您可以定义当前的年份:
$cur_date = new DateTime();
$cur_year = $cur_date->format('y');有了这些东西,您将从if statement获得所需的结果。
if($st_date <= $cmp_date && $cmp_date <= $end_date && $cur_year == $dtp_year)
{
echo 'OK';
}else{
echo 'NO';
} 发布于 2019-12-28 09:31:34
移动到更多最新方法的时间,这些方法允许轻松地比较日期:
$startDate = new DateTime('05/01 this year');
$endDate = new DateTime("09/30 this year");
$curDate = new DateTime(); // will give you current date
var_dump($curDate > $startDate && $curDate < $endDate);关于datetime的更多信息(包括格式)是在手册中。
发布于 2019-12-28 10:26:19
如果您想使此代码具有动态,那么只需将日期转换为数字月份即可。
$comparisonDate = strtotime("04/30/20");
$eventDate=(int)date('m',$comparisonDate); //the date return string which is converted as int
if($eventDate >= 5 & $eventDate <= 9 ){echo "success";}https://stackoverflow.com/questions/59509588
复制相似问题