c# - 比较没有年份的 DateTime

标签 c# datetime

我正尝试在客户在接下来的 7 天内过生日时收到提醒。

我已经用这段代码试过了:

public bool IsBirthdayImminent
{
    get { return DateOfBirth != null && DateOfBirth.Value.Date >= DateTime.Today.Date.AddDays(-7); }
}

当然这是行不通的,因为日期与它的年份一起存储(比如 05/21/1980)并且它还会比较年份。所以这个查询永远不会是 true - 好吧,如果你在接下来的 7 天内出生就不会。

如何修改此查询以忽略年份?

编辑:

好吧,查询本身完全没有问题。我的主要观点是处理闰年和 12 月 <-> 1 月左右的情况。

最佳答案

我建议使用以下代码。这包括 12 月至 1 月和 2 月 29 日前后的病例。尽管您可能想查看并更正 2 月 28 日,以便在给定的 days 内包含或排除。

    BirthdayImminent(new DateTime(1980, 1, 1), new DateTime(2012, 1, 2), 7); // false
    BirthdayImminent(new DateTime(1980, 1, 1), new DateTime(2012, 12, 28), 7); // true
    BirthdayImminent(new DateTime(1980, 2, 28), new DateTime(2012, 2, 21), 7); // true

    private static bool BirthdayImminent(DateTime birthDate, DateTime referenceDate, int days)
    {
        DateTime birthdayThisYear = birthDate.AddYears(referenceDate.Year - birthDate.Year);

        if (birthdayThisYear < referenceDate)
            birthdayThisYear = birthdayThisYear.AddYears(1);

        bool birthdayImminent = (birthdayThisYear - referenceDate).TotalDays <= days;

        return birthdayImminent;
    }

还要记住边缘情况Guvante发表在下面的评论中。

关于c# - 比较没有年份的 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16947949/

相关文章:

c# - string.compare 和 string 进行比较

python - 使用 python 的 strptime 解析带有任何分隔符的日期

mysql - 检查 MySql 日期时间是否为空的更好方法

c# - AutoComplete 是否适用于 WPF?

java - android 字符串到日期的转换

python - 修复某些行中日期和月份互换的日期字符串

bash - 在 bash 中按日期排序文件列表

c# - 使用 HtmlAgilityPack 获取同一域上的所有链接

c# - 使用 NEST C# 客户端搜索 ElasticSearch

c# - 具有多个 Where 子句的 Linq 过滤结果