Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • I am getting all sorts of problems using this function, for instance if you mock 'theDate = DateTime.Now.AddMinutes(-40);' I am getting '40 hours ago', but with Michael's refactormycode response, it returns correct at '40 minutes ago' ? Commented Dec 15, 2008 at 2:17
  • i think you are missing a zero, try: long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000; Commented Aug 7, 2009 at 19:37
  • 9
    Hmm, while this code may work it is incorrect and invalid to assume that the order of the keys in the Dictionary will be in a specific order. The Dictionary uses the Object.GetHashCode() which does not return a long but an int!. If you want these to be sorted then you should use a SortedList<long, string>. What is wrong with the thresholds being evaluated in a set of if/else if/.../else ? You get the same number of comparisons. FYI the hash for long.MaxValue turns out to be the same as int.MinValue! Commented Nov 9, 2011 at 4:47
  • OP forgot t.Days > 30 ? t.Days / 30 : Commented Oct 31, 2012 at 10:39
  • To fix the issue mentioned by @CodeMonkeyKing, you could use a SortedDictionary instead of a plain Dictionary: The usage is the same, but it ensures that the keys are sorted. But even then, the algorithm has flaws, because RelativeDate(DateTime.Now.AddMonths(-3).AddDays(-3)) returns "95 months ago", regardless which dictionary type you're using, which is incorrect (it should return "3 months ago" or "4 months ago" depending on which threshold you're using) - even if -3 does not create a date in the past year (I have tested this in December, so in this case it should not happen). Commented Nov 22, 2016 at 12:00