How to test two dateTimes for being the same date?

C#DatetimeEquality

C# Problem Overview


> 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

C# Solutions


Solution 1 - C#

Try

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB. Clay Shannon-B. Crow RavenView Question on Stackoverflow
Solution 1 - C#BrandonView Answer on Stackoverflow