C #: How to compare two dates

I want to compare the date stored in the table in the form DD/MM/YYYYwith the current date.

I need to know if it is sooner or later than DateTime.Now...

Anyone have an idea to suggest?

Thanks in advance.

+3
source share
3 answers

You can use DateTime.Comparefor this:

var result = DateTime.Compare(Convert.ToDateTime(TextBox1.Text), DateTime.Today);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);

See the MSDN documentation for more details .

+5
source

You can use the following code to analyze your timestamps in DateTime objects, and then compare them as you wish.

DateTime date;
DateTime.TryParseExact("12/03/2009", "dd/MM/yyyy", null, DateTimeStyles.None, out date);

More details here http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

+1
source

DateTime.Compare :

date1 = Convert.ToDateTime(TextBox1.Text)
date2 = DateTime.Today
var result = DateTime.Compare(date1, date2)
string relationship

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
0

All Articles