Given a specific DateTime
value, how do I display relative time, like:
- 2 hours ago
- 3 days ago
- a month ago
original title: "datetime - Calculate relative time in C#"
Given a specific DateTime
value, how do I display relative time, like:
एक विशिष्ट दिनांक समय को देखते हुए, मैं सापेक्ष समय कैसे प्रदर्शित करूं, जैसे: 2 घंटे पहले 3 दिन पहले एक महीने पहले
यह अनुवाद के बाद का सारांश है, अगर आपको पूरा अनुवाद देखने की आवश्यकता है, तो कृपया 'अनुवाद' आइकन पर क्लिक करें
Jeff, your code is nice but could be clearer with constants (as suggested in Code Complete).
jquery.timeago plugin
Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin.
Benefits:
Just attach it to your timestamps on DOM ready:
This will turn all
abbr
elements with a class of timeago and an ISO 8601 timestamp in the title:into something like this:
which yields: 4 months ago. As time passes, the timestamps will automatically update.
Disclaimer: I wrote this plugin, so I'm biased.
Here's how I do it
Suggestions? Comments? Ways to improve this algorithm?
I prefer this version for its conciseness, and ability to add in new tick points. This could be encapsulated with a
Latest()
extension to Timespan instead of that long 1 liner, but for the sake of brevity in posting, this will do. This fixes the an hour ago, 1 hours ago, by providing an hour until 2 hours have elapsedHere a rewrite from Jeffs Script for PHP:
http://refactormycode.com/codes/493-twitter-esque-relative-dates
C# 6 version:
Here's an implementation I added as an extension method to the DateTime class that handles both future and past dates and provides an approximation option that allows you to specify the level of detail you're looking for ("3 hour ago" vs "3 hours, 23 minutes, 12 seconds ago"):
I would recommend computing this on the client side too. Less work for the server.
The following is the version that I use (from Zach Leatherman)
There are also a package called Humanizer on Nuget and it actually works really well
Scott Hanselman has a writeup on it on his blog
@jeff
IMHO yours seems a little long. However it does seem a little more robust with support for "yesterday" and "years". But in my experience when this is used the person is most likely to view the content in the first 30 days. It is only the really hardcore people that come after that. So that is why I usually elect to keep this short and simple.
This is the method I am currently using on one of my websites. This only returns a relative day, hour, time. And then the user has to slap on "ago" in the output.
A couple of years late to the party, but I had a requirement to do this for both past and future dates, so I combined Jeff's and Vincent's into this. It's a ternarytastic extravaganza! :)
Is there an easy way to do this in Java? The
java.util.Date
class seems rather limited.Here is my quick and dirty Java solution:
iPhone Objective-C Version
Given the world and her husband appear to be posting code samples, here is what I wrote a while ago, based on a couple of these answers.
I had a specific need for this code to be localisable. So I have two classes —
Grammar
, which specifies the localisable terms, andFuzzyDateExtensions
, which holds a bunch of extension methods. I had no need to deal with future datetimes, so no attempt is made to handle them with this code.I've left some of the XMLdoc in the source, but removed most (where they'd be obvious) for brevity's sake. I've also not included every class member here:
The
FuzzyDateString
class contains:One of the key things I wanted to achieve, as well as localisation, was that "today" would only mean "this calendar day", so the
IsToday
,IsThisMonth
,IsThisYear
methods look like this:and the rounding methods are like this (I've included
RoundedMonths
, as that's a bit different):I hope people find this useful and/or interesting :o)
using Fluent DateTime
In PHP, I do it this way:
I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate "months ago" that didn't seem too over-engineered.
I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected).
For the below code PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago) returns the relative time message (e.g. "yesterday").
When you know the viewer's time zone, it might be clearer to use calendar days at the day scale. I'm not familiar with the .NET libraries so I don't know how you'd do that in C#, unfortunately.
On consumer sites, you could also be hand-wavier under a minute. "Less than a minute ago" or "just now" could be good enough.
The same as another answer to this question but as an extension method with a static dictionary.
you can try this.I think it will work correctly.
@Jeff
Doing a subtraction on
DateTime
returns aTimeSpan
anyway.So you can just do
I'm also surprised to see the constants multiplied-out by hand and then comments added with the multiplications in. Was that some misguided optimisation?
Java for client-side gwt usage:
Here's the algorithm stackoverflow uses but rewritten more concisely in perlish pseudocode with a bug fix (no "one hours ago"). The function takes a (positive) number of seconds ago and returns a human-friendly string like "3 hours ago" or "yesterday".
You can use TimeAgo extension from which looks like the following:
Or use jQuery plugin with Razor extension from Timeago.
You can reduce the server-side load by performing this logic client-side. View source on some Digg pages for reference. They have the server emit an epoch time value that gets processed by Javascript. This way you don't need to manage the end user's time zone. The new server-side code would be something like:
You could even add a NOSCRIPT block there and just perform a ToString().
This, I got from one of Bill Gates' blog. I need to find it on my browser history and I'll give you the link.
The Javascript code to do the same thing (as requested):
Basically, you work in terms of seconds...
I think there is already a number of answers related to this post, but one can use this which is easy to use just like plugin and also easily readable for programmers. Send your specific date, and get its value in string form:
If you want to have an output like
"2 days, 4 hours and 12 minutes ago"
, you need a timespan:Then you can access the values you like:
etc...
I would provide some handy extensions methods for this and make the code more readable. First, couple of extension methods for
Int32
.Then, one for
DateTime
.Now, you can do something like below: