0

I have tried several of the examples mentioned on stackoverflow about this issue, but I can't figure out why the returns I get are inconsistent with expected behaviour. I'm trying to get every user that had their birthday last month. Birthdays are stored as follows: d-m-yyyy. The following sample code shows the issue:

    $start = "01-10-2019";
    $end = "31-10-2019";
    $test = "01-11-1968";
    $start_date = date("d-m", strtotime($start));
    $end_date = date("d-m", strtotime($end));
    $test_date = date("d-m", strtotime($test));

    if(($test_date >= $start_date) && ($test_date <= $end_date))
    {
        error_log("date is in between");
    } else
    {
        error_log("is not");
    }

This code returns "date is in between", even though the expected return is "is not". It seems that everything date before $start gives the proper return, but everything after $end does not.

2 Answers2

2

Here would be my solution with DateTime objects.

Edit: Be aware that the parameters are passed by reference. So the years of the objects get overwritten by the current year.

Edit2: The function no longer touches the specified DateTime objects.

<?php

$start = "01-10-2019";
$end = "31-10-2019";
$test = "01-11-1968";

$start = new \DateTime($start);
$end = new \DateTime($end);
$test = new \DateTime($test);

function isBetweenDateIgnoreYear(\DateTime $startInput, \DateTime $endInput, \DateTime $checkInput)
{
    $start = clone $startInput;
    $end = clone $endInput;
    $check = clone $checkInput;

    $currentYear = (int) date('Y');
    $start->setDate($currentYear, (int) $start->format('m'), (int) $start->format('d'));
    $end->setDate($currentYear, (int) $end->format('m'), (int) $end->format('d'));
    $check->setDate($currentYear, (int) $check->format('m'), (int) $check->format('d'));

    return ($start <= $check && $check <= $end);
}

$result = isBetweenDateIgnoreYear($start, $end, $test);
var_dump($result);
Fred
  • 868
  • 10
  • 22
0

Make use of the unix date format as that is a simple number like this

$start = "01-10-2019";
$end = "31-10-2019";
$test = "01-11-1968";
$start_date = strtotime($start);
$end_date = strtotime($end);
// get d and m and from DOB and replace Year with current year
$test_date = strtotime( date("d-m", strtotime($test)) . '-' . date('Y') );

if(($test_date >= $start_date) && ($test_date <= $end_date))
{
    echo "date is in between";
} else {
    echo "is not";
}

Why yours didnt work:

You were comparing for example 01-11 and 31-10 those will not compare nicely.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149