Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how do i compare dates in C#. example d1 = february 1, 2012, d2 = january 1, 2012

condition d2 must be greater than d1 if not an error prompt occur

how do i do this?

thanks in advance
Posted

This is only a simple example and I advise you to use TryParse instead of parse, but the example is sufficient to illustrate what to do:

C#
static void Main()
{
    DateTime d1 = DateTime.Parse("February 1, 2012"); // Better to use TryParse here
    DateTime d2 = DateTime.Parse("January  1, 2012"); // ditto

    if (DateTime.Compare(d1, d2) < 0) // also possible to use d1.CompareTo(d2). If the result is less than zero d1 is less than d2
    //if (d1 < d2) // As Youssef pointed out the normal relational less than or greater than operator can also be used
    {
        Console.WriteLine("Everything OK!");
    }
    else
    {
        Console.WriteLine("Do what ever you see fit in the error case!");
    }
}
 
Share this answer
 
v3
Comments
newbie011292 23-Feb-12 11:10am    
thank you
Manfred Rudolf Bihy 23-Feb-12 11:35am    
You're welcome!
Uday P.Singh 23-Feb-12 11:52am    
5!
It is easy and normal, my friend:
C#
if(d1 < d2)
{
    // Code in case of correct date relation
}
else
{
    // Code in case of error (d2 less than or equal to d1)
}
 
Share this answer
 
v2
Comments
youssef_123 23-Feb-12 9:48am    
but they must be both of type DateTime
newbie011292 23-Feb-12 11:11am    
thank you
Use the TimeSpan Compare method[^].
 
Share this answer
 
Comments
Manfred Rudolf Bihy 23-Feb-12 9:58am    
I think you wanted to say DateTime.CompareTo or the static counterpart DateTime.Compare. There is no need for a Timespan here.
newbie011292 23-Feb-12 11:11am    
thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900