70

Possible Duplicate:
How to compare Dates in C#

This code of mine:

public static string getLogFileNameForDate(DateTime dt)
{
    if (dt.Equals(DateTime.Now))

...fails even when the two dates are the same (date) because dt is assigned a value at startup (e.g. "6/18/2012 15:19:42"), and so the dates are not exactly the same, even though the year, month, and day are the same (value of DateTime.Now may be, say, "6/18/2012 15:30:13").

I know I can test it this way:

if ((dt.Year.Equals(DateTime.Now.Year) && (dt.Month.Equals(DateTime.Now.Month) && (dt.Day.Equals(DateTime.Now.Day))

...but that seems a bit Jethro*-like

What is the accepted/preferred method (no pun intended)?

  • Clampett, not Tull
Community
  • 1
  • 1
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    dt.Date.CompareTo(DateTime.Now.Date) == 0 should do the trick. – dash Jun 18 '12 at 22:33
  • 2
    Oh, and http://stackoverflow.com/questions/683037/how-to-compare-dates-in-c-sharp – dash Jun 18 '12 at 22:38
  • @dash: Looks like you need the mythical "Seeing Double" badge for these dupes you keep finding. – Austin Salonen Jun 18 '12 at 22:40
  • I just keep asking myself: "Surely these can't be original questions" :-) On one hand, it's good the OP get's an answer, but on the other, filling the site with the same answers... – dash Jun 18 '12 at 22:40

1 Answers1

154

Try

if (dt.Date == DateTime.Now.Date)

It will only take the date portion and the timestamp will be 12:00:00

Brandon
  • 68,708
  • 30
  • 194
  • 223