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

时间:2011-10-22 01:35:05

标签: c# .net datetime

我正在从数据库中读取日期到期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方法的想法。

6 个答案:

答案 0 :(得分:10)

public bool HasPassed2hoursFrom(DateTime fromDate, DateTime expireDate) 
{
    return expireDate - fromDate > TimeSpan.FromHours(2);
}

答案 1 :(得分:3)

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.Now非常快,你不需要将它作为函数参数...

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

答案 2 :(得分:3)

bool HasPassed2hoursFrom(DateTime now, DateTime expires)
{
    return (now - expires).TotalHours >= 2;
}

答案 3 :(得分:2)

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

答案 4 :(得分:0)

您可以使用运算符

boolean hasExpired = now >= Expires;

答案 5 :(得分:0)

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&MSPPError=-2147217396