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.
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
}

- 234,701
- 27
- 340
- 448
-
18Better use `DateTime.Today` than `DateTime.Now.Date` if u don't need hours, minutes etc – Piotr Auguscik Jul 06 '11 at 06:14
-
@Piotr - good point - unless they also need to access hours/minutes/seconds as another part of the work. – Damien_The_Unbeliever Jul 06 '11 at 06:17
-
1@Damien_The_Unbeliever Will this work for any date format? What about `yyyy/MM/dd` ? – SamuraiJack Sep 26 '13 at 06:56
-
3@Arbaaz - once you've converted whatever *string* you have into a `DateTime`, then as I said in my answer, it no longer *has* a format. It has an internal representation, and the framework knows how to perform appropriate comparisons. – Damien_The_Unbeliever Sep 26 '13 at 11:50
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.

- 6,537
- 2
- 25
- 38
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!
}

- 24,298
- 12
- 47
- 62