How to check if a DateTime occurs today?

后端 未结 13 1252
故里飘歌
故里飘歌 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).

提交回复
热议问题