了解日期是否在两个日期之间,忽略年份 [英] Find out if date is between two dates, ignoring year

查看:128
本文介绍了了解日期是否在两个日期之间,忽略年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定一个日期(月和日)是否在两个月/日之间。

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

我附上了一个图片,描述了什么我想要做基本上,当前日的示例以红色突出显示,并且在最近的日期之间(3月15日和11月22日)。然而,当我使用Unix时间戳和人为地添加一年的时间时,脚本认为11月22日还没有发生,因此它表明2月1日是在3月15日和11月22日之前,而不是在它们之间。所以,我需要比较日期而不使用一年。

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.

推荐答案

您的示例中的问题是(在同一年)下边界之前的上限日期是。在这种情况下,任何小于上限(1月1日至3月14日)或大于下限(11月23日至12月31日)的日期在两者之间。

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);
?>

显示:
boolean true

如果要查看的日期是Feb 29,而当年不是闰年,然后DateTime将其解释为3月1日。

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;
}

这篇关于了解日期是否在两个日期之间,忽略年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆