Comparing only dates with DateTime C #

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 in which 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 the dates using the code below, but this gives me a 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, not part of the time. Therefore, I used the ToShortDateString method.

+3
source share
2 answers

Just use the property :Date DateTime

if (SelDate.Date >= sTime.Date)

Also note that you can use DateTime.Todayto start today.

+7
source

Just use the Date property for DateTime and do a direct comparison.

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

if( SelDate.Date >= sTime.Date )
{
   // do something here
}
+2
source

Source: https://habr.com/ru/post/1768101/


All Articles