Skip to content

Instantly share code, notes, and snippets.

@aljungberg
Created November 30, 2010 20:32
Show Gist options
  • Save aljungberg/722346 to your computer and use it in GitHub Desktop.
Save aljungberg/722346 to your computer and use it in GitHub Desktop.
[date timeAgo] method which returns a string like "about a minute"
/*
* Created by Alexander Ljungberg on May 17, 2010.
* Copyright 2010, WireLoad, LLC All rights reserved.
*
* Based on jQuery's timeago by Ryan McGeary.
*
* Original code is:
* Licensed under the MIT:
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright (c) 2008-2010, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org)
*/
var TimeAgoSettings = {
refreshMillis: 60000,
allowFuture: false,
strings: {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "ago",
suffixFromNow: "from now",
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years"
}
};
var distance = function(date) {
return (new Date().getTime() - date.getTime());
}
var substitute = function(string, value) {
return string.replace(/%d/i, value);
}
@implementation CPDate (TimeAgo)
- (CPString)timeAgo
{
var distanceMillis = distance(self),
l = TimeAgoSettings.strings,
prefix = l.prefixAgo,
suffix = l.suffixAgo || l.ago;
if (TimeAgoSettings.allowFuture)
{
if (distanceMillis < 0)
{
prefix = l.prefixFromNow;
suffix = l.suffixFromNow || l.fromNow;
}
distanceMillis = Math.abs(distanceMillis);
}
var seconds = distanceMillis / 1000,
minutes = seconds / 60,
hours = minutes / 60,
days = hours / 24,
years = days / 365;
var words = seconds < 45 && substitute(l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute(l.minute, 1) ||
minutes < 45 && substitute(l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute(l.hour, 1) ||
hours < 24 && substitute(l.hours, Math.round(hours)) ||
hours < 48 && substitute(l.day, 1) ||
days < 30 && substitute(l.days, Math.floor(days)) ||
days < 60 && substitute(l.month, 1) ||
days < 365 && substitute(l.months, Math.floor(days / 30)) ||
years < 2 && substitute(l.year, 1) ||
substitute(l.years, Math.floor(years));
return [[prefix, words, suffix].join(" ") stringByTrimmingWhitespace];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment