How to check if a date has passed in C#?

前端 未结 6 1422
执笔经年
执笔经年 2021-01-05 03:24

I\'m reading the date expires cookie (2 hours) from database, and I need to check if this date has passed. What\'s the best way to do this?

For example:

<         


        
6条回答
  •  情深已故
    2021-01-05 04:03

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

    But since DateTime.Now is very fast and you don't need to pass it as function parameter...

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

提交回复
热议问题