2

How to check if month exist in specific period ($date1 and $date2)

$month = '2016-01';
$date1 = '2016-01-05';
$date2 = '2016-02-04;
Maged Hamid
  • 952
  • 1
  • 9
  • 18
  • 3
    Can you provide a more explicit definition of what you mean by "if $month exists between two dates"? For example, are you asking for a way to determine if the specific date 2016-01-01 occurs between $date1 and $date2? – Nate Dec 30 '15 at 21:25
  • No I want to know if The month 01 on year 2016 exist between $date1 and $date2? – Maged Hamid Dec 30 '15 at 21:43
  • Okay, but what precisely does "between" mean for you? For example, if $date1 is 2015-12-30 and $date2 is 2016-01-02, then does month 01 exist "between" them? And if $date1 is 2016-01-29 and $date2 is 2016-01-30, then does month 01 exist "between" them? If $date1 is 2016-01-30 and $date2 is 2016-02-15, does month 01 exist "between" them? See the potential ambiguity inherent in your question? – Nate Dec 30 '15 at 21:51
  • sorry for my bad English i edit the question to How to check if month exist in specific period or during this period ( 2016-01-05 to 2016-02-04 ) – Maged Hamid Dec 30 '15 at 21:57

3 Answers3

2

First convert the month into a date, like the first day of the month. Then you can compare the dates to check if the month lies in between:

$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)) ) 
    { }
Erik Kalkoken
  • 30,467
  • 8
  • 79
  • 114
0

I got a best answer for my question on his link The Answer

This answer get months between two dates

$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 
}
Community
  • 1
  • 1
Maged Hamid
  • 952
  • 1
  • 9
  • 18
-1

You could search the strings using strpos(). http://php.net/manual/en/function.strpos.php

ex:

if (strpos($date1,$month) || strpos($date2,$month)){/* do stuff */}
asebold
  • 193
  • 11
  • Be careful, as this would only work if the month was the same as the starting or ending month. It would not work if the desired month was in between the two – bhooks Dec 30 '15 at 22:07