Thursday, 6 June 2013

Compare two dates in .NET based on Day



Compare two DateTimes:

DateTime date1=Convert.ToDateTime("06-01-2013");
DateTime date1=Convert.ToDateTime("06-01-2013");

int days = DateTime.Compare(date1, date2);

* days > 0      date1  is greaterthan date2
* days = 0      date1 and d2 are equal
* days < 0      date1 is lesserthan date2

But the problem with DateTime is it will compare with exact values with time also.


Compare only two Dates :

TimeSpan ts= date1 - date2;

TimeSpan will return exact days & hours and we need to extract the days from it and we can compare.

* ts.Days > 0      date1  is greaterthan date2
* ts.Days= 0       date1 and d2 are equal
* ts.Days <  0     date1 is lesserthan date2  

Here ts.Days will give you exact days..

No comments:

Post a Comment