How to compare Date?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I would like to know how to compare date in C#?

e.g. System.DateTime.Now > 2005-10-17 19:55:04

Thanks
 
Hi Tom,

You can use DateTime.Compare/CompareTo or Subtract one date from the other and check the resulting TimeSpan.
All versions require that you create a DateTime object out of 2005-10-17 19:55:04
 
Hi,

You can use the usual operators to compare two datetimes instances.

In what format the second date is? it's a string?
if so you first need to convert it to DateTime , you can use DateTime.Parse
or DateTime.ParseExact , the difference is that the latter let you especify
the format used in the string expression.

Additionally you can use Convert.ToDateTime

cheers,
 
Hi,

Can I write:

Convert.ToDateTime(string_date).CompareTo(System.DateTime.Now) < 0

If so, is the current date time AFTER the stringdate?
 
Yes.

If it is 0, they are equal; greater than 0, current date is smaller.


Hi,

Can I write:

Convert.ToDateTime(string_date).CompareTo(System.DateTime.Now) < 0

If so, is the current date time AFTER the stringdate?
 
Tom said:
Can I write:

Convert.ToDateTime(string_date).CompareTo(System.DateTime.Now) < 0

If so, is the current date time AFTER the stringdate?

You could do that, but it would be simpler to write:

if (DateTime.Now > Convert.ToDateTime (string_date))
 
Hi,


You can, but it's what you want?

Take a look at this:
Console.WriteLine( DateTime.Now > DateTime.Now.Date ); // you could also use
Console.WriteLine( DateTime.Now.CompareTo( DateTime.Now.Date ));

You will see they are different !
The reason?
DateTime.Now is taking the time part into account, where the
DateTime.Now.Date is not.

IF in your case string_date refer only to the date part you should use
DateTime.Now.Date to make the comparison.


cheers,
 
Back
Top