Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to compare two dates

Tags:

c#

datetime

I want to compare a date stored in a table in the form DD/MM/YYYY with the current date.

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

Does someone have an idea to suggest?

Thank you in advance.

like image 343
Omar AMEZOUG Avatar asked Jun 10 '26 04:06

Omar AMEZOUG


2 Answers

You can use DateTime.Compare for 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 documentation on MSDN for more details.

like image 155
James Johnson Avatar answered Jun 11 '26 16:06

James Johnson


You can use the following code to parse your time stamps into DateTime objects and then compare as you like.

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

See more here http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

like image 21
Thomas Avatar answered Jun 11 '26 17:06

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!