如何在C#中检查日期是否已过

本文关键字:日期 是否 检查 | 更新日期: 2023-09-27 18:11:55

我正在从数据库中读取日期过期cookie(2小时(,我需要检查这个日期是否已经过去。最好的方法是什么?

例如:

public bool HasExpired(DateTime now)
{
    string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
    DateTime Expires = DateTime.Parse(expires);
    return HasPassed2hoursFrom(now, Expires);
}

我正在寻找关于编写.HasPassed2hoursFrom方法的想法。

如何在C#中检查日期是否已过

public bool HasPassed2hoursFrom(DateTime fromDate, DateTime expireDate) 
{
    return expireDate - fromDate > TimeSpan.FromHours(2);
}
bool HasPassed2hoursFrom(DateTime now, DateTime expires)
{
    return (now - expires).TotalHours >= 2;
}
public bool HasExpired(DateTime now)
{
    string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
    DateTime Expires = DateTime.Parse(expires);
    return now.CompareTo(Expires.Add(new TimeSpan(2, 0, 0))) > 0;
}

但从DateTime开始。现在非常快,不需要将其作为函数参数传递。。。

public bool HasExpired()
{
    string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
    DateTime Expires = DateTime.Parse(expires);
    return DateTime.Now.CompareTo(Expires.Add(new TimeSpan(2, 0, 0))) > 0;
}

定期检查日期,查看now.CompareTo(expires) > 0 是否

您可以只使用运算符

boolean hasExpired = now >= Expires;
private enum DateComparisonResult
    {
        Earlier = -1,
        Later = 1,
        TheSame = 0
    };
    void comapre()
    {
        DateTime Date1 = new DateTime(2020,10,1);
        DateTime Date2 = new DateTime(2010,10,1);
        DateComparisonResult comparison;
        comparison = (DateComparisonResult)Date1.CompareTo(Date2);
        MessageBox.Show(comparison.ToString());    
    }
    //Output is "later", means date1 is later than date2 

检查日期是否已过:

来源:https://msdn.microsoft.com/en-us/library/5ata5aya%28v=vs.110%29.aspx?f=255&MSPP错误=-2147217396