Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing just dates from DateTime C#

Tags:

c#

wpf

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.

like image 251
developer Avatar asked Apr 14 '26 06:04

developer


2 Answers

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.

like image 60
Jon Skeet Avatar answered Apr 15 '26 21:04

Jon Skeet


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
}
like image 28
Justin Avatar answered Apr 15 '26 21:04

Justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!