开发者

Comparing just dates from 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 wherein the user can select a date,

C# Logic:
DateTime SelDate;
            if (datePicker.SelectedDate == null)
                SelDate = DateTime.Now; 
            else
                SelDate = date开发者_如何学运维Picker.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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜