0

i have a datetime value and i compare to now. I try to convert the two dates to int because are different type.

this is a my code:

Int64 NowDate = Convert.ToInt64(DateTime.Now.ToString("yyyyMMddhhmmss"));

return mylist.Where(f => Convert.ToInt64(f.DateStart.ToString("yyyyMMddhhmmss")) > NowDate).ToList();

it works but if your of day is 21.00.00 i have a problem, convert.toint64 remove the 00.00 and my number is < nowdate.

Billy D.
  • 15
  • 4
  • 4
    False assumption. A DateTime is a DateTime. There is no need to convert to int. Did you try _f.DateStart < DateTime.Now_ ? – Steve Apr 27 '17 at 09:12
  • 3
    Possible duplicate of [How to compare dates in c#](http://stackoverflow.com/questions/6592126/how-to-compare-dates-in-c-sharp) –  Apr 27 '17 at 09:13

2 Answers2

0

To compare two dates in C#, you don't have to do any type conversions.

You can just write

mydate < DateTime.Now

And it will work !

Because DateTime implements IComparable, that means you can compare two Dates between one another

Irwene
  • 2,807
  • 23
  • 48
0

Converting the Datetime to string creates lots of problems. For me, you should keep the dates as date. And you should try a query like this :

return mylist.Where(f => f.DateStart> Datetime.Now).ToList();

If you want to compare only dates, you can use :

 return mylist.Where(f => f.DateStart.Date > Datetime.Now.Date).ToList();

Attention, if your DateStart field is nullable, it can throw an exception. In this case you should control null values.

Coskun Ozogul
  • 2,389
  • 1
  • 20
  • 32