1
votes

I'm having difficulties creating a date algorithm (using the DateTime object) that checks to see if a date lands between two given months (where the end of the year is considered Aug 31st).

So the beginning of the year is considered Sept 1st, XXXX and end of the year is considered Aug 31st XXXX+1

$today = new DateTime('now');

I need to see if date is between June and May.

For example if it is Dec 2009
Is the date between June 2009 and May 2010? (yes)

If date is April 2014
Is the date between June 2013 and May 2014? (yes)

If date is July 2014
Is date between June 2013 and May 2014. (no)

2
Why don't you just use the Numeric representation of a month and compare that?Bryan Allo
@BryanAllo, so the problem with that is I need to determine what year it is in as well. If The date is August 1 2014, it is in the 2013-2014 year. If the date is Sept 4, 2015, it is in the 2015-2016 yearkylex
Why not convert to UNIX timestamps and do your comparisons?IROEGBU
@kylex - Yes. What I meant is basically use the date_add() method and offset your date by 4 months to bring it back in line with the standard calendar and then do your comparison/check.Bryan Allo

2 Answers

1
votes

DateTime objects can be compared just like two integers:

$date1 = new DateTime('December 2012');
$date2 = new DateTime('June 2012');
$date3 = new DateTime('May 2013');

if ($date1 > $date2 && $date1 < $date3)
{
     // place your code here
}
0
votes

Found an answer that got me started:

https://stackoverflow.com/a/11937688/36545

function academicYear(DateTime $userDate) {
    $currentYear = $userDate->format('Y');
    $cutoff = new DateTime($userDate->format('Y') . '/08/31 23:59:59');
    if ($userDate < $cutoff) {
        return ($currentYear-1) . '/' . $currentYear;
    }
    return $currentYear . '/' . ($currentYear+1);
}