Jack
Jack

Reputation: 16724

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

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:

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

I'm looking for ideas as write the .HasPassed2hoursFrom method.

Upvotes: 8

Views: 18714

Answers (6)

Hassaan Raza
Hassaan Raza

Reputation: 91

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 

To check if date has passed:

Source:https://msdn.microsoft.com/en-us/library/5ata5aya%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Upvotes: 0

Joao
Joao

Reputation: 7486

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

Upvotes: 13

Marcel Valdez Orozco
Marcel Valdez Orozco

Reputation: 3015

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

Upvotes: 5

smunk
smunk

Reputation: 324

You can just use operators

boolean hasExpired = now >= Expires;

Upvotes: 1

Salvatore Previti
Salvatore Previti

Reputation: 9050

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

Upvotes: 4

Ryder
Ryder

Reputation: 351

Periodically check the date and see if now.CompareTo(expires) > 0

Upvotes: 4

Related Questions