2

i was looking for date compare in LINQ and i found a code from searching google.

var currentDate = DateTime.Now.Date;

VisitorLog log = db.Context.VisitorLogs .Where(vl=>vl.inDate.Date == currentDate).FirstOrDefault();

i need to know the above code works fine or not.

how do i compare date in particular format like i compare date in sql server

compare(varchar(10),mydatefield,112)>=compare(varchar(10),@mydatefield,112)

so please guide me how could i compare date using linq in particular format like above one.

thanks

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
Mou
  • 15,673
  • 43
  • 156
  • 275

3 Answers3

2

The thing is that you will rarely compare dates in a specific format(unless you want to compare them as strings or something). Thus is the introduction of the DateTime structure.

Anyway the most used way of comparing dates is not to check for equality but to actually check whether a date comes into a specific range. For example:

startDate <= order.OrderDate && order.OrderDate < endDate
TheBoyan
  • 6,802
  • 3
  • 45
  • 61
  • i want to convert date in specific format and then compare. i want to convert date like YYYYMMDD this format and then compare. how it would be possible with linq date comparision. – Mou Jul 04 '11 at 11:24
  • 1
    That's the whole point, you don't do that. The whole point of parsing the date into a DateTime struct is not to have to deal with formats. DateTime has fields (like year, day, month) that you compare. Otherwise you would just be comparing strings. – TheBoyan Jul 04 '11 at 11:44
1

Can this link help you?

How to compare dates in LINQ?

where t.CreateDate.Date < DateTime.Today.AddMonths(-1)
Community
  • 1
  • 1
cesara
  • 842
  • 1
  • 7
  • 19
0

The format matters when you parse a string to a DateTime object. Once you have done that and you have two DateTime objects then comparing their Date properties is the correct thing to do. The Date properties return DateTime objects with time set to 12:00am

In order to parse the date correctly you can pass a IFormatProvider to the DateTime.Parse() method. E.g. a CultureInfo object:

DateTime d = DateTime.Parse("07/04/2011", CultureInfo.GetCultureInfo("en-us"));
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95