Is there a better .net way to check if a DateTime has occured \'today\' then the code below?
if ( newsStory.WhenAdded.Day == DateTime.Now.Day &&
If NewsStory was using a DateTime also, just compare the Date property, and you're done.
However, this depends what "today" actually means. If something is posted shortly before midnight, it will be "old" after a short time. So maybe it would be best to keep the exact story date (including time, preferably UTC) and check if less than 24 hours (or whatever) have passed, which is simple (dates can be subtracted, which gives you a TimeSpan with a TotalHours or TotalDays property).
You can implement a DateTime extension method.
Create new class for your extension methods:
namespace ExtensionMethods
{
public static class ExtensionMethods
{
public static bool IsSameDay( this DateTime datetime1, DateTime datetime2 )
{
return datetime1.Year == datetime2.Year
&& datetime1.Month == datetime2.Month
&& datetime1.Day == datetime2.Day;
}
}
}
And now, everywhere on your code, where do you want to perform this test, you should include the using:
using ExtensionMethods;
And then, use the extension method:
newsStory.WhenAdded.IsSameDay(DateTime.Now);
you could use DateTime.Now.DayOfYear
if (newsStory.DayOfYear == DateTime.Now.DayOfYear)
{ // story happened today
}
else
{ // story didn't happen today
}
Try
if (newsStory.Date == DateTime.Now.Date)
{ /* Story happened today */ }
else
{ /* Story didn't happen today */ }
Try this:
newsStory.Date == DateTime.Today
How about
if (newsStory.DayOfYear == DateTime.Now.DayOfYear)
{ // Story happened today
}
But this will also return true for 1st January 2008 and 1st January 2009, which may or may not be what you want.