1

i got 3 different Datetimes. $start_date and $end_date are the given range of dates i work with. What i need is to find the $date_from_user in this range, what is not the problem, i found plenty of solutions for that, like this SO answer.

But what i need is then to tell what exact day the $date_from_user is in the given Daterange.

So taken from the example below the expected result would be 5.

$start_date = '2009-09-05';

$end_date = '2009-09-17';

$date_from_user = '2009-09-10';

How can i get the number of the day from the range?

I thought for myself about an for loop to compare the date, but that would be problematic if the Daterange is larger than a month.

Community
  • 1
  • 1
KhorneHoly
  • 4,666
  • 6
  • 43
  • 75
  • `$date_table=explode("-",$start_date);` then : `$years = $date_table[0];` `$month = $date_table[1];` `$day = $date_table[2];` echo $years; --> 2009 echo $month; --> 09 echo $day; --> 05 – angel May 26 '14 at 09:33
  • @angel I can't understand what is reasonable of working with date as string. – Lkopo May 26 '14 at 09:39

2 Answers2

2
$date_from = '2014-5-25';
$date_from = strtotime($date_from);

$date_to = '2014-6-4';
$date_to = strtotime($date_to);

for ($i = $date_from; $i <= $date_to; $i += 86400) {
    $dates[] = date("Y-n-j", $i);
}
return $dates

Try the above

SuperDJ
  • 7,488
  • 11
  • 40
  • 74
  • Worked for me, but i would love to ask one little thing: If i echo `$dates[5]` i will get `2009-9-10` what is like expected. But if i do `$day = array_search($date_from_user, $dates);` `$day` will not display anything. What am i doing wrong? – KhorneHoly May 26 '14 at 09:53
  • Okay, fixed it by myself, $date_from_user wasn't a string, which caused problems – KhorneHoly May 26 '14 at 10:30
1

You should be using the DateTime classes for date calculations. They are very flexible and will take into account DST, timezones and leap years. I am at a loss as to why people are still using strtotime().

Effectively, all you need to do is count the number of days from the start of the range to the user provided date after checking that user has provided a date within the required range.

A function similar to this would work for you:-

function getDayNumberInRange($start, $end, $dayToFind)
{
    $format = 'Y-m-d';
    $startDate = \DateTime::createFromFormat($format, $start);
    $endDate = \DateTime::createFromFormat($format, $end);
    $toFind = \DateTime::createFromFormat($format, $dayToFind);

    if($toFind < $startDate || $toFind > $endDate){
        throw new InvalidArgumentException('The date to find must be between the start and end of the range.');
    }

    return $toFind->diff($startDate)->days;
}

$start_date = '2009-09-05';
$end_date = '2009-09-17';
$date_from_user = '2009-09-10';

echo getDayNumberInRange($start_date, $end_date, $date_from_user); // 5
vascowhite
  • 18,120
  • 9
  • 61
  • 77