Skip to content

Instantly share code, notes, and snippets.

@tzhbami7
Created July 4, 2013 13:44
Show Gist options
  • Save tzhbami7/5927854 to your computer and use it in GitHub Desktop.
Save tzhbami7/5927854 to your computer and use it in GitHub Desktop.
time interval
//Constants
#define SECOND 1
#define MINUTE (60 * SECOND)
#define HOUR (60 * MINUTE)
#define DAY (24 * HOUR)
#define MONTH (30 * DAY)
- (NSString*)timeIntervalWithStartDate:(NSDate*)d1 withEndDate:(NSDate*)d2
{
//Calculate the delta in seconds between the two dates
NSTimeInterval delta = [d2 timeIntervalSinceDate:d1];
if (delta < 1 * MINUTE)
{
return delta == 1 ? @"one second ago" : [NSString stringWithFormat:@"%d seconds ago", (int)delta];
}
if (delta < 2 * MINUTE)
{
return @"a minute ago";
}
if (delta < 45 * MINUTE)
{
int minutes = floor((double)delta/MINUTE);
return [NSString stringWithFormat:@"%d minutes ago", minutes];
}
if (delta < 90 * MINUTE)
{
return @"an hour ago";
}
if (delta < 24 * HOUR)
{
int hours = floor((double)delta/HOUR);
return [NSString stringWithFormat:@"%d hours ago", hours];
}
if (delta < 48 * HOUR)
{
return @"yesterday";
}
if (delta < 30 * DAY)
{
int days = floor((double)delta/DAY);
return [NSString stringWithFormat:@"%d days ago", days];
}
if (delta < 12 * MONTH)
{
int months = floor((double)delta/MONTH);
return months <= 1 ? @"one month ago" : [NSString stringWithFormat:@"%d months ago", months];
}
else
{
int years = floor((double)delta/MONTH/12.0);
return years <= 1 ? @"one year ago" : [NSString stringWithFormat:@"%d years ago", years];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment