1

My mind seems to be going blank on this one.

I have to write something to figure out which date range todays day/month combination fits into.

I have a set amount of date ranges, which are:

  $dateRanges = array(
    1 => "16 January to 30 April",
    2 => "1 May to 30 June",
    3 => "1 July to 15 August",
    4 => "16 August to 15 September",
    5 => "15 September to 15 October",
    6 => "16 October to 15 January"
  );

All I'm trying to return is the array key of the range the current date fits into.

At the moment all thats going through my head is I'll have to set up a large if statement to look at the current date('j') and date('n') and match the results up. But surely thats pretty messy and not very efficient?

Any ideas of a better way to approach this problem would be much appreciated!

Nick
  • 6,316
  • 2
  • 29
  • 47

4 Answers4

5
$today = time();
foreach ($dateRanges as $key => $range) {
   list($start, $end) = explode(' to ', $range);
   $start .= ' ' . date('Y'); // add 2011 to the string
   $end .= ' ' . date('Y');
   if ((strtotime($start) <= $today) && (strtotime($end) >= $today)) {
       break;
   }
}

$key will be either the index of the matching date range, or null/false.

Marc B
  • 356,200
  • 43
  • 426
  • 500
2

This is a variation on Mark B's answer, but made more efficient by turning this into pure numeric comparisons:

function get_today () {
  $dateRanges = array(
    0 => 116, // 16th Jan
    1 => 501, // 1st May
    2 => 701, // 1st July ..etc..
    3 => 816,
    4 => 916,
    5 => 1016
  );
  $today = (int) date('nd');
  foreach ($dateRanges as $key => $date) {
    if ($today < $date) {
      $result = $key;
      break;
    }
  }
  return (empty($result)) ? 6 : $result;
}

Returns an integer matching the keys in your sample array

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
0

Create DateTime instances for the values in the array und use simple comparison operators like > and <

CodeZombie
  • 5,367
  • 3
  • 30
  • 37
0

Just use strtotime to create a UNIX epoch, then use the inbuilt < and > operators.

http://www.php.net/manual/en/function.strtotime.php

$time_min = strtotime("17 January 2011");
$time_max = strtotime("30 April 2011");
if ($time >= $time_min && $time < $time_max)
{
    echo "Time is within range!";
}

You can then just expand this to use the array of ranges you specified.

Polynomial
  • 27,674
  • 12
  • 80
  • 107