locked
Comparing Dates RRS feed

  • Question

  • Hi,

     

    I want to check if one date is less (i.e. earlier) than the other.

     

    How do I do this??

     

    Thanks.

    Wednesday, April 30, 2008 12:04 PM

Answers

  • simply compare the DateTime objects.

     

    DateTime myDateTime = DateTime.Now.AddDays(1);

    if (DateTime.Now < myDateTime)

    {

       //do whatever

    }

     

    Wednesday, April 30, 2008 12:09 PM

All replies

  • simply compare the DateTime objects.

     

    DateTime myDateTime = DateTime.Now.AddDays(1);

    if (DateTime.Now < myDateTime)

    {

       //do whatever

    }

     

    Wednesday, April 30, 2008 12:09 PM
  • While Ahmedilyas answer is, strictly speaking, right; I think a bit of elaboration on the topic could be useful to better understand the concept. Maybe some of what I'll say here you already know, but better to make sure.

     

    The first and most essential point to mention is the fact that the .NET framework provides a DateTime type expressely dessigned to handle dates and times. If you are not using it, then you should. You can create a DateTime object using any one of the many constructors provided by the struct, or using the DateTime.Parse(String) method (or any of its variations). You can find more on this type at http://msdn.microsoft.com/en-us/library/system.datetime.aspx.

     

    The second, and quite interesting, point is that the DateTime type provides several useful operators; among them the comparation operators. So, once you have your dates in DateTime variables, you can use the <, <=, >, >=, ==, and != operators with the obvious results, just as Ahmedilyas mentioned.

     

    To put a simple example, let's say you get the dates in strings, comming from TextBox'es (mostly to illustrate how to convert them), you could have code like this:

    private bool IsEarlier(string Date1, string Date2) {

    Code Snippet

    DateTime d1, d2;

    d1=DateTime.Parse(Date1);

    d2=DateTime.Parse(Date2);

    return (d1 < d2);

    }

     

    or even something much more compact:

    Code Snippet

    private bool IsEarlier(string Date1, string Date2) {

    return (DateTime.Parse(Date1) < DateTime.Parse(Date2));

    }

     

    Of course, if you already have the dates in DateTime objects, you can skip the conversions and just compare them with the "<" operator when needed.

     

    I hope this helps putting some context to the question, and maybe even helps you to better understand Ahmedilyas' original reply.

    Also, if you need to do anything else with your dates, check the link I put earlier on this post (or simply look for DateTime in VS's help): you'll find a lot of useful information there, and several links to even more information Wink

    Friday, May 2, 2008 4:44 PM