Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if date is between two dates, ignoring year

Tags:

date

php

I need to determine if a date (month and day) is between two other month/days.

I've attached an image to this post that describes what I'm trying to do. Basically the example "current day" is highlighted in red, and it's between those nearest dates (Mar 15 and Nov 22). However, when I use Unix timestamps and artificially add a year to the dates, the script thinks that Nov 22 hasn't occurred yet, and therefore it suggests that Feb 1 is before Mar 15 AND Nov 22, instead of in between them. So, I need to compare dates without using a year.

Hopefully this makes sense. I'd just like to compare dates using months and days, but ignoring the year, and using a framework like the wheel I show in the image.

Determine if date falls between two dates

like image 292
user1610717 Avatar asked Jul 09 '13 04:07

user1610717


People also ask

How do I find the difference between two dates in Excel without Datedif?

Just subtract one date from the other. For example if cell A2 has an invoice date in it of 1/1/2015 and cell B2 has a date paid of 1/30/2015, then you could enter use the formula =B2-A2 to get the number of days between the two dates, or 29.


1 Answers

The problem in your example is that (in the same year) the upper bounding date is before the lower bound. In that case, Any date less than the upper bound (Jan 1 - Mar 14) or greater than the lower bound (Nov 23 - Dec 31) falls between the two.

<?php
    $upperBound = new DateTime("Mar 15");
    $lowerBound = new DateTime("Nov 22");
    $checkDate = new DateTime("Feb 1");

    if ($lowerBound < $upperBound) {
        $between = $lowerBound < $checkDate && $checkDate < $upperBound;
    } else {
        $between = $checkDate < $upperBound || $checkDate > $lowerBound;
    }
    var_dump($between);
?>

Displays: boolean true

Edit

If the date you want to check is "Feb 29" and the current year is not a leap year, then DateTime interprets it as "Mar 1".

To check if a date falls between two dates, inclusively, use:

if ($lowerBound < $upperBound) {
    $between = $lowerBound <= $checkDate && $checkDate <= $upperBound;
} else {
    $between = $checkDate <= $upperBound || $checkDate >= $lowerBound;
}
like image 113
Herbert Avatar answered Oct 25 '22 12:10

Herbert