Skip to content

Instantly share code, notes, and snippets.

@Haar
Last active December 23, 2015 11:39
Show Gist options
  • Save Haar/6629487 to your computer and use it in GitHub Desktop.
Save Haar/6629487 to your computer and use it in GitHub Desktop.
Simple RelativeDate utility class for displaying dates relative to now. [date relativeString] == 3 days ago, 24 years from now, 2 seconds ago, etc.
//
// NSDate+RelativeDate.h
// RWRelativeDate
//
// Created by Robert White on 19/09/2013.
//
#import <Foundation/Foundation.h>
@interface NSDate (RelativeDate)
- (NSString *)relativeString;
@end
//
// NSDate+RelativeDate.m
// RWRelativeDate
//
// Created by Robert White on 19/09/2013.
//
#import "NSDate+RelativeDate.h"
@implementation NSDate (RelativeDate)
- (NSString *)relativeString
{
NSTimeInterval timeInterval = [self timeIntervalSinceNow];
NSString *relativity;
if (timeInterval < 0) {
relativity = @"ago";
timeInterval = timeInterval * -1;
} else {
relativity = @"from now";
}
NSInteger time;
NSString *unit;
if (timeInterval <= 60) {
time = floor(timeInterval);
unit = @"second";
} else if (timeInterval <= 3600) {
time = floor(timeInterval / 60);
unit = @"minute";
} else if (timeInterval <= 86400) {
time = floor(timeInterval / 3600);
unit = @"hour";
} else if (timeInterval <= 604800) {
time = floor(timeInterval / 86400);
unit = @"day";
} else if (timeInterval <= 2419200) {
time = floor(timeInterval / 604800);
unit = @"week";
} else if (timeInterval <= 31557600) {
time = floor(timeInterval / 2419200);
unit = @"month";
} else if (timeInterval <= [[NSDate distantFuture] timeIntervalSinceNow]){
time = floor(timeInterval / 31557600);
unit = @"year";
} else {
return [NSString stringWithFormat: @"a long, long time %@...", relativity];
}
if (time > 1) unit = [NSString stringWithFormat:@"%@s", unit];
return [NSString stringWithFormat:@"%d %@ %@", time, unit, relativity];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment