如何使用PHP检查特定时期内是否存在月份

时间:2015-12-30 21:22:35

标签: php date

如何检查特定时期内是否存在月份($ date1和$ date2)

$month = '2016-01';
$date1 = '2016-01-05';
$date2 = '2016-02-04;

3 个答案:

答案 0 :(得分:2)

首先将月份转换为日期,例如该月的第一天。然后,您可以比较日期以检查月份是否介于两者之间:

$month_day = date ('Y-m-01', strtotime($month) );
$date1_day = date ('Y-m-01', strtotime($date1) );
$date2_day = date ('Y-m-01', strtotime($date2) );

if ( ($month_day >= min($date1_day, $date2_day)) 
      && ($month_day <= max($date1_day, $date2_day)) ) 
    { }

答案 1 :(得分:0)

我的链接The Answer

上的问题得到了最佳答案

这个答案在两个日期之间得到了几个月

$start    = (new DateTime('2016-01-05'))->modify('first day of this month');
$end      = (new DateTime('2016-02-04'))->modify('first day of this month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);
$monthsArray = [];
foreach ($period as $dt) {
    $monthsArray[] = $dt->format("Y-m"); // I put months exist in this period on array to check later if the $month exist on this array or not 
}

答案 2 :(得分:-1)

您可以使用strpos()搜索字符串。 http://php.net/manual/en/function.strpos.php

例如:

if (strpos($date1,$month) || strpos($date2,$month)){/* do stuff */}