KhorneHoly
KhorneHoly

Reputation: 4766

How to get the number of a day in given daterange

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.

Upvotes: 1

Views: 57

Answers (2)

vascowhite
vascowhite

Reputation: 18430

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

Upvotes: 1

SuperDJ
SuperDJ

Reputation: 7661

$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

Upvotes: 2

Related Questions