Ago.js converts timestamps to human-readable time without relying on bloated libraries.
Examples: 1 minute ago, 3 days ahead, 3 weeks ago, 5 months ahead, just now
You can use the awesome jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/gh/jomo/ago.js@0.0.1/ago.min.js" integrity="sha256-xw0JUUdbuZQCVO+QScoxrlEsD4nZGCjMRh9PP8GLhcY=" crossorigin="anonymous"></script>If you use HTML <time> tags, all you need is
<time datetime="2014-09-10T18:34:13+00:00">2014-09-10T18:34:13+00:00</time>Ago();Results look like this:
<time datetime="2014-09-10T18:34:13+00:00">2 months ago</time>Ago() takes two optional arguments:
- nodes, an array of HTML nodes you want to use.
The default isdocument.querySelectorAll("time") - options, see below
You can customize Ago.js by overriding the default options.
- interval: milliseconds-interval in which nodes should be updates
- units: Array of arrays with ["unit name", seconds]
- date: function(node) that returns a
Datefor the given node - format: function(time, unit) that returns a string which will be used for a node's text
- plural: Object that contains all
unitswith their plural as value
{
interval: 10000, // 10 secs
units: [
["minute", 60],
["hour", 3600],
["day", 86400],
["week", 604800],
["month", 2592000],
["year", 31536000]
],
date: function(node) {
// works on HTML <time> nodes
return new Date(node.getAttribute("datetime"));
},
format: function(time, unit) {
if (!unit) return "just now";
var tail = time < 0 ? " ahead" : " ago";
return Math.abs(time) + " " + unit + tail;
},
plural: {
minute: "minutes",
hour: "hours",
day: "days",
week: "weeks",
month: "months",
year: "years"
}
}<div>
Last updated
<span class="ago", data-time="2014-11-16T21:08:39+00:00">
2014-11-16T21:08:39+00:00
</span>
</div>Ago(document.querySelectorAll(".ago"), {
date: function(node) {
return new Date(node.getAttribute("data-time"));
}
});Ago({
format: function(time, unit) {
time = Math.abs(time);
if (!unit) return "just now";
if (time === 1) time = (unit[0] == "h") ? "an" : "a";
var tail = time < 0 ? " ahead" : " ago";
return time + " " + unit + tail;
}
});// German
Ago({
units: [
["Minute", 60],
["Stunde", 3600],
["Tag", 86400],
["Woche", 604800],
["Monat", 2592000],
["Jahr", 31536000]
],
plural: {
Minute: "Minuten",
Stunde: "Stunden",
Tag: "Tagen",
Woche: "Wochen",
Monat: "Monaten",
Jahr: "Jahren"
},
format: function(time, unit) {
if (!unit) {
return "jetzt";
}
if (time < 0) {
var lead = "in ";
} else {
var lead = "vor ";
}
return lead + Math.abs(time) + " " + unit;
}
});Example: in 22 Stunden
If you like this, you can buy me a beer at 1jomojdTww1vnNwvseLrKgTENZoojQ3Um