Created
October 5, 2010 06:40
-
-
Save fightinjoe/611131 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSDate+Pretty.m | |
// AaronWheeler | |
// | |
// Created by Aaron Wheeler on 10/4/10. | |
// Copyright 2010 n/a. All rights reserved. | |
// | |
#import "NSDate+Pretty.h" | |
@interface NSDate (Pretty) | |
- (NSString *) toAgoString; | |
@end | |
@implementation NSDate (Pretty) | |
// Pretty prints the date as a string, formatted as "<unit of time> ago", | |
// for example, "3 days ago" or "25 minutes ago" | |
- (NSString *) toAgoString { | |
// Ported from John Resig's Pretty Date JS function | |
// http://ejohn.org/files/pretty.js | |
NSTimeInterval diff = -1 * [self timeIntervalSinceNow]; | |
NSTimeInterval dayDiff = floor(diff / 86400); | |
NSLog(@"Date: %@ and diff: %f and dayDiff: %f, %f", self, diff, dayDiff, dayDiff / 30.0); | |
if ( dayDiff < 0.0 ) { return @""; } | |
else if ( diff < 60.0 ) { return @"just now"; } | |
else if ( diff < 120.0 ) { return @"1 minute ago"; } | |
else if ( diff < 3600.0 ) { return [NSString stringWithFormat:@"%.f minutes ago", floor(diff/60.0)]; } | |
else if ( diff < 7200.0 ) { return @"1 hour ago"; } | |
else if ( diff < 86400.0 ) { return [NSString stringWithFormat:@"%.f hours ago", floor(diff/3600.0)]; } | |
else if ( dayDiff == 1.0 ) { return @"Yesterday"; } | |
else if ( dayDiff < 7.0 ) { return [NSString stringWithFormat:@"%.f days ago", dayDiff]; } | |
else if ( dayDiff < 62.0 ) { return [NSString stringWithFormat:@"%.f weeks ago", ceil( dayDiff / 7.0 )]; } | |
// Up to 15 months | |
else if ( dayDiff < 455.0 ){ return [NSString stringWithFormat:@"%.f months ago", ceil( dayDiff / 30.0 )]; } | |
else if ( dayDiff < 730.5 ){ return @"1 year ago"; } | |
else { return [NSString stringWithFormat:@"%.f years ago", ceil( dayDiff / 365.25 )]; } | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment