From e48868e253f7c467d2e91b460f6d61325d7f4231 Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Mon, 5 Sep 2011 21:24:06 -0700 Subject: [PATCH] add future dates to -[NSDate relativeToNow] --- Marshmallows/NSDate+relative.m | 54 +++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/Marshmallows/NSDate+relative.m b/Marshmallows/NSDate+relative.m index c6da255..68e99be 100644 --- a/Marshmallows/NSDate+relative.m +++ b/Marshmallows/NSDate+relative.m @@ -13,15 +13,58 @@ #define DAY (24.0 * HOUR) #define WEEK (7.0 * DAY) #define MONTH (30.0 * DAY) +#define YEAR (365.25 * DAY) @implementation NSDate (NSDate_relative) - (NSString *) relativeToNow { double diff = [[NSDate date] timeIntervalSinceDate: self]; - if (diff < MINUTE) { + + // future + if (diff < -2 * YEAR) { + return [NSString stringWithFormat: @"in %d years", abs(diff / YEAR)]; + } + else if (diff < -YEAR) { + return @"next year"; + } + else if (diff < -8 * WEEK) { + return [NSString stringWithFormat: @"in %d months", abs(diff / MONTH)]; + } + else if (diff < -4 * WEEK) { + return @"next month"; + } + else if (diff < -2 * WEEK) { + return [NSString stringWithFormat: @"in %d weeks", abs(diff / WEEK)]; + } + else if (diff < -WEEK) { + return @"next week"; + } + else if (diff < -2 * DAY) { + return [NSString stringWithFormat: @"in %d days", abs(diff / DAY)]; + } + else if (diff < -DAY) { + return @"tomorrow"; + } + else if (diff < -2 * HOUR) { + return [NSString stringWithFormat: @"in %d hours", abs(diff / HOUR)]; + } + else if (diff < -HOUR) { + return @"in an hour"; + } + else if (diff < -2 * MINUTE) { + return [NSString stringWithFormat: @"in %d minutes", abs(diff / MINUTE)]; + } + else if (diff < -MINUTE) { + return @"in a minute"; + } + + // present + else if (diff < MINUTE) { return @"right now"; } + + // past else if (diff < 2 * MINUTE) { return @"a minute ago"; } @@ -49,12 +92,15 @@ else if (diff < 8 * WEEK) { return @"last month"; } - else if (diff < 12 * MONTH) { + else if (diff < YEAR) { return [NSString stringWithFormat: @"%d months ago", (int)(diff / MONTH)]; } + else if (diff < 2 * YEAR) { + return @"last year"; + } else { - return @"a long time ago"; - } + return [NSString stringWithFormat: @"%d years ago", (int)(diff / YEAR)]; + } } @end