How to check if a DateTime occurs today?

后端 未结 13 1249
故里飘歌
故里飘歌 2020-12-08 18:01

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 &&
             


        
相关标签:
13条回答
  • 2020-12-08 18:26

    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).

    0 讨论(0)
  • 2020-12-08 18:28

    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);
    
    0 讨论(0)
  • 2020-12-08 18:28

    you could use DateTime.Now.DayOfYear

     if (newsStory.DayOfYear == DateTime.Now.DayOfYear)
     { // story happened today
    
     }
     else
     { // story didn't happen today
    
     }
    
    0 讨论(0)
  • 2020-12-08 18:31

    Try

    if (newsStory.Date == DateTime.Now.Date) 
    { /* Story happened today */ }
    else
    { /* Story didn't happen today */ }
    
    0 讨论(0)
  • 2020-12-08 18:36

    Try this:

    newsStory.Date == DateTime.Today
    
    0 讨论(0)
  • 2020-12-08 18:36

    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.

    0 讨论(0)
提交回复
热议问题