How to check if a DateTime occurs today?

后端 未结 13 1250
故里飘歌
故里飘歌 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:39
    if( newsStory.Date == DateTime.Today )
    {
        // happened today
    }
    
    0 讨论(0)
  • 2020-12-08 18:39

    My solution:

    private bool IsTheSameDay(DateTime date1, DateTime date2)
    {
        return (date1.Year == date2.Year && date1.DayOfYear == date2.DayOfYear);
    }
    
    0 讨论(0)
  • 2020-12-08 18:39

    if (newsStory.ToShortDateString() == DateTime.Today.ToShortDateString()) return "Todtay";

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

    FYI,

    newsStory.Date == DateTime.Today

    will return the same compare result as coding

    newsStory == DateTime.Today

    where newsStory is a DateTime object

    .NET is smart enough to determine you want to compare based on Date only and uses that for the internal Compare. Not sure why, and actually having trouble finding documentation for this behaviour.

    0 讨论(0)
  • 2020-12-08 18:48
    if (newsStory.WhenAdded.Date == DateTime.Today)
    {
    
    }
    else
    {
    
    }
    

    Should do the trick.

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

    As Guillame suggested in a comment, compare values of Date properties:

    newStory.Date == DateTime.Now.Date
    
    0 讨论(0)
提交回复
热议问题