tags:

views:

79

answers:

2

Hi, My table contains 2 fields with values,

StartTime                 EndTime
  3/6/2010 8:00:00 AM       3/6/2010 10:20:00 AM

Now I have a datepicker control wherein the user can select a date,

C# Logic:
DateTime SelDate;
            if (datePicker.SelectedDate == null)
                SelDate = DateTime.Now; 
            else
                SelDate = datePicker.SelectedDate;

I am trying to compare dates by the below code but it gives me compile time error,

foreach (DomainObject obj in res.ResultSet)
                    {
                        MyClass adef = (MyClass)obj;
                        DateTime sTime = (DateTime)adef.StartTime;
                        DateTime eTime = (DateTime)adef.EndTime;

                        if ((SelDate.ToShortDateString >= sTime.ToShortDateString) && (SelDate.ToShortDateString <= eTime.ToShortDateString))
                        {
                            actdef.Add(new MyClassViewModel(adef));
                        }

                    }

I just want to take the date for comparison and not the time part. So I have used the ToShortDateString method.

+6  A: 

Just use the Date property of DateTime:

if (SelDate.Date >= sTime.Date)

Also note that you can use DateTime.Today to get the start of today.

Jon Skeet
+2  A: 

Just use the Date property of the DateTime and do a straight comparison.

DateTime SelDate = datePicker.SelectedDate == null ? DateTime.Now : datePicker.SelectedDate;

if( SelDate.Date >= sTime.Date )
{
   // do something here
}
Justin