0

I am trying to get the number of days between two datetimes, but not according to the exact timespan, rather according to the "day date" difference between date a and date b. No hours taken in account.

So far, I calculated the age of an item using :

(DateTime.Now - creationDate).Days

The problem with this code is that, for something that was created the day before but less than 24h ago, it will output "0 days", which is not very clear to my users apparently.

So what I want to accomplish is, even for an item that was created at 11:59pm for example, to get an output of "1 day old" as soon as the clock hits midnight. How could I accomplish this?

SylvainB
  • 4,765
  • 2
  • 26
  • 39
  • This question should be interresting for you : http://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site – Larry Feb 23 '13 at 13:23
  • @Laurent: I don't see how that's relevant in this case. – Jon Skeet Feb 23 '13 at 13:25
  • You're right. I assumed that the problem behind is to display a clear time span to the user. So I gave that link as a comment in the case of it may inspire some idea. – Larry Feb 23 '13 at 13:35

2 Answers2

3

Two options:

1) Take the two dates first:

    var days = (DateTime.Today - creationDate.Date).Days;

2) Use my Noda Time date/time library instead, using LocalDate for the two dates involved, and then Period.Between(start, end, PeriodUnits.Days) to get a period of just days. (You can also get weeks, months etc.) Admittedly getting "today's date" is deliberately a bit trickier in Noda Time - where .NET implicitly uses "the system time zone," Noda Time forces you to be more explicit.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

I would use it simply like

int days =(int)DateTime.Now.Subtract(creationDate).TotalDays; 

hope this helps

Faaiz Khan
  • 332
  • 1
  • 4