标签云

微信群

扫码加入我们

WeChat QR Code

Given a specific DateTime value, how do I display relative time, like:

  • 2 hours ago
  • 3 days ago
  • a month ago


What if you want to calculate a relative time from now to Future?

2018年07月19日26分18秒

moment.js is a very nice date parsing library.. You can consider using that (server side or client side), depending on your needs. just fyi because nobody mentioned it here

2018年07月18日26分18秒

There is the .net package github.com/NickStrupat/TimeAgo which pretty much does what is being asked.

2018年07月19日26分18秒

I hate such constants with a passion. Does this look wrong to anyone? Thread.Sleep(1 * MINUTE)? Because it's wrong by a factor of 1000.

2018年07月19日26分18秒

const int SECOND = 1; So weird a second is one second.

2018年07月19日26分18秒

This type of code is nearly impossible to localize. If your app only needs to remain in English, then fine. But if you make the jump to other languages, you will hate yourself for doing logic like this. Just so y'all know...

2018年07月19日26分18秒

I think if the constants were renamed to accurately describe the value that is in them, it'd be easier to understand. So SecondsPerMinute = 60; MinutesPerHour = 60; SecondsPerHour = MinutesPerHour * SecondsPerHour; etc. Just calling it MINUTE=60 doesn't allow the reader to determine what the value is.

2018年07月18日26分18秒

Why nobody (except Joe) care about the wrong 'Yesterday' or 'days ago' value ??? Yesterday is not an hour calculation, but a day to day calculation. So yes, this is a wrong code at least in two frequent case.

2018年07月18日26分18秒

Seb, If you have Javascript disabled, then the string you originally put between the abbr tags is displayed. Typically, this is just a date or time in any format you wish. Timeago degrades gracefully. It doesn't get much simpler.

2018年07月18日26分18秒

Ryan, I suggested that SO use timeago a while ago. Jeff's response made me cry, i suggest you sit down: stackoverflow.uservoice.com/pages/1722-general/suggestions/…

2018年07月19日26分18秒

Heh, Thanks Rob. That's okay. It's barely noticeable, especially when only one number changes during the transition, though SO pages have a lot of timestamps. I would have thought he would have at least appreciated the benefits of page caching though, even if he chooses to avoid auto-updates. I'm sure Jeff could have provided feedback to improve the plugin too. I take solace knowing sites like arstechnica.com use it.

2018年07月18日26分18秒

Rob Fonseca-Ensor - now it's making me cry too. How is an update once per minute, to show accurate information, in any way related to text blinking once a second?

2018年07月18日26分18秒

The question is about C#, I fail to see how a jQuery plugin is relevant.

2018年07月18日26分18秒

"< 48*60*60s" is a rather unconventional definition for "yesterday". If it's 9am on Wednesday, would you really think of 9:01am on Monday as "yesterday". I'd have thought an algorithm for yesterday or "n days ago" should consider before/after midnight.

2018年07月19日26分18秒

Compilers are usually pretty good at pre-calculating constant expressions, like 24 * 60 * 60, so you can directly use those instead of calculating it yourself to be 86400 and putting the original expression in comments

2018年07月19日26分18秒

noticed that this function excludes weeks

2018年07月18日26分18秒

bzlm I think I did for a project I was working on. My motivation here was to alert others that weeks were omitted from this code sample. As to how to do that, it seemed pretty straight forward to me.

2018年07月18日26分18秒

I think that good way to improve algorithm is displaying 2 units like "2 month 21 days ago", "1 hour 40 minutes ago" for increasing accuracy.

2018年07月18日26分18秒

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' ?

2018年07月18日26分18秒

i think you are missing a zero, try: long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000;

2018年07月18日26分18秒

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!

2018年07月18日26分18秒

OP forgot t.Days > 30 ? t.Days / 30 :

2018年07月18日26分18秒

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

2018年07月18日26分18秒

The question is C# tagged Why PHP code ?

2018年07月18日26分18秒

this is very nice IMO :) This could also be refactored as an extension method? could the dictionary become static so it's only created once and referenced from then after?

2018年07月19日26分18秒

Pure.Krome: stackoverflow.com/questions/11/how-do-i-calculate-relative-time/…

2018年07月18日26分18秒

You'd probably want to pull that dictionary out into a field so that you reduce instantiation and GC churn. You'd have to change Func<string> to Func<double>.

2018年07月18日26分18秒

in javascript - jsfiddle.net/drzaus/eMUzF

2018年07月18日26分18秒

The question is C# tagged Why Javascript code ?

2018年07月18日26分18秒

friendly note: On .net 4.5 or above don't install complete Humanizer... only install Humanizer.Core part of it.. cause other language packages are not supported on this version

2018年07月18日26分18秒

So useful! This answer must be much much higher in this list. If I had 100 votes, I'd give it to this. Apparently (coming from JS-land), searching for this package was not easy.

2018年07月19日26分18秒

The question is C# tagged Why Java code ?

2018年07月18日26分18秒

The question is C# tagged. Why this PHP code ? IMHO, only applies C# code

2018年07月18日26分18秒

What does the dictionary buy you here?

2018年07月19日26分18秒

StriplingWarrior: Ease of reading and modifying compared to a switch statement or a stack of if/else statements. The dictionary being static means that it and the Func<,> objects don't have to be created every time we want to use ToRelativeDate; it's created only once, compared to the one I linked in my answer.

2018年07月18日26分18秒

I see. I was just thinking, since the documentation on Dictionary states that "The order in which the items are returned is undefined," (msdn.microsoft.com/en-us/library/xfhwa508.aspx) perhaps that's not the best data structure to use when you don't care about lookup times as much as having things stay in order.

2018年07月18日26分18秒

StriplingWarrior: I believe LINQ takes that into account when used with Dictionarys. If you're still uncomfortable with it, you can use SortedDictionary, but my own experience shows that to be unnecessary.

2018年07月18日26分18秒

The question is C# tagged. Why this Java code ? IMHO, only applies C# code

2018年07月18日26分18秒