The DateTime. Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000 .
today() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.
You can use equal to comparison operator = to check if one datetime object is has same value as other. In the following program, we initialize two datetime objects, and then check if both datetime objects have same date and time.
Now has an approximate resolution of 10 milliseconds on all NT operating systems. The actual precision is hardware dependent.
if (newsStory.WhenAdded.Date == DateTime.Today)
{
}
else
{
}
Should do the trick.
if( newsStory.Date == DateTime.Today )
{
// happened today
}
Try
if (newsStory.Date == DateTime.Now.Date)
{ /* Story happened today */ }
else
{ /* Story didn't happen today */ }
My solution:
private bool IsTheSameDay(DateTime date1, DateTime date2)
{
return (date1.Year == date2.Year && date1.DayOfYear == date2.DayOfYear);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With