Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test two dateTimes for being the same date? [duplicate]

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
like image 705
B. Clay Shannon-B. Crow Raven Avatar asked Jun 18 '12 22:06

B. Clay Shannon-B. Crow Raven


People also ask

How do you know if two dates are the same day?

To check if two dates are the same day, call the toDateString() method on both Date() objects and compare the results. If the output from calling the method is the same, the dates are the same day.


1 Answers

Try

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

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

like image 185
Brandon Avatar answered Sep 20 '22 07:09

Brandon