I'd like to display some dates as relative to the current date in a human-friendly format.
Examples of human-friendly relative dates:
- 10 seconds ago
- 20 minutes from now
- 1 day ago
- 5 weeks ago
- 2 months ago
Basically faithfully preserving the highest order of magnitude (and by preference, only shifting up units when passing 2 of those units - 5 weeks instead of 1 month).
Though I could live with a library that had less control and even more friendly dates like:
- yesterday
- tomorrow
- last week
- a few minutes ago
- in a couple hours
Any popular libraries for this?
Since I wrote this answer, a well known library available is moment.js.
There are libraries available, but it is trivial to implement it yourself. Just use a handful of conditions.
Assume
date
is an instantiatedDate
object for the time you want to make a comparison against.You would need to adapt this to handle future dates.
I wrote a small date library that does this. It's about
2k136K (46K minimized), and works in browsers and in Node.moment.js
It supports timeago, formatting, parsing, manipulating, i18n, etc.
Also, the timeago strings are customizable, so you can change them how you see fit.
The cutoffs are not as you would prefer (5 weeks vs 1 month), but they are documented on which strings are used in what time range.
This js script is very nice. All you have to do is to execute it. All
<time>
tags will be changed to relative dates and updated every few minutes, so the relative time will always be up to date.http://timeago.yarp.com/
Here's something from the John Resig - http://ejohn.org/blog/javascript-pretty-date/
EDIT (6/27/2014): Following up on the comment from Sumurai8 - though the linked page still works, here is the excerpt for the
pretty.js
linked to from the article above:pretty.js
Usage:
Excerpt from the article on usage:
With JavaScript:
With jQuery:
Faiz: Made some changes to the original code, bug fixes and improvements.
Sounds like you could use http://www.datejs.com/
They have an example on the main page that does exactly what you're describing!
EDIT: Actually, I think I reversed your question in my head. In any case, I think you could check it out as it's a really great library anyway!
EDIT x2: I'm going to echo what the others have said http://momentjs.com/ is probably the best choice available right now.
EDIT x3: I haven't used date.js in over a year. I'm exclusively using momentjs for all my date related needs.
sugar.js has great date formatting functions.
Not only that, it also provides common general purpose functions like string formatting, number formatting, etc. that are convenient to use.