Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates in c#

Tags:

c#

datetime

I have two dates. One date is input and other is DateTime.Now. I have them in mm/dd/yyyy format, it can even be m/d/yy format also. Both dates are nullable i.e, datatype is DateTime?, since I can pass null also as input. Now I want to compare the two dates only with mm/dd/yyyy or m/d/yy format.

like image 852
shafi Avatar asked Jul 06 '11 05:07

shafi


People also ask

How can I compare two dates?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.


3 Answers

If you have your dates in DateTime variables, they don't have a format.

You can use the Date property to return a DateTime value with the time portion set to midnight. So, if you have:

DateTime dt1 = DateTime.Parse("07/12/2011"); DateTime dt2 = DateTime.Now;  if(dt1.Date > dt2.Date) {      //It's a later date } else {      //It's an earlier or equal date } 
like image 109
Damien_The_Unbeliever Avatar answered Sep 16 '22 13:09

Damien_The_Unbeliever


If you have date in DateTime variable then its a DateTime object and doesn't contain any format. Formatted date are expressed as string when you call DateTime.ToString method and provide format in it.

Lets say you have two DateTime variable, you can use the compare method for comparision,

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0); DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0); int 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"; 

Code snippet taken from msdn.

like image 41
FIre Panda Avatar answered Sep 19 '22 13:09

FIre Panda


Firstly, understand that DateTime objects aren't formatted. They just store the Year, Month, Day, Hour, Minute, Second, etc as a numeric value and the formatting occurs when you want to represent it as a string somehow. You can compare DateTime objects without formatting them.

To compare an input date with DateTime.Now, you need to first parse the input into a date and then compare just the Year/Month/Day portions:

DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
    throw new ArgumentException("Input string not in the correct format.");

if(inputDate.Date == DateTime.Now.Date) {
    // Same date!
}
like image 42
BC. Avatar answered Sep 18 '22 13:09

BC.