Converting Timestamp to NSString Providing the Difference to “Just Now”

If you got a timestamp, e.g. from an SQL database entry, and you need a NSString on iOS that tells you how many seconds, minutes, hours, etc. ago this event happened (to display to the user), NSDateComponents is your friend.

Here is a small utility method that illustrates the conversion:

+ (NSString*)timeAgoString:(NSString *)timestampString
{
    double eventSecondsSince1970 =
        [timestampString doubleValue] / 1000.0; // milliseconds to seconds
    NSDate *eventDate =
        [NSDate dateWithTimeIntervalSince1970:eventSecondsSince1970];
    NSCalendar *gregorian =
        [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
        autorelease];
    int unitFlags = NSYearCalendarUnit |
                    NSMonthCalendarUnit |
                    NSDayCalendarUnit |
                    NSHourCalendarUnit |
                    NSMinuteCalendarUnit |
                    NSSecondCalendarUnit;
    NSDateComponents *comps =
        [gregorian components:unitFlags
        fromDate:eventDate toDate:[NSDate date] options:0];

    NSString *timeAgoString = [NSString string];
    if ([comps year] > 0) {
        timeAgoString =
            [NSString stringWithFormat:@"%i years ago", [comps year]];
    }
    else if ([comps month] > 0) {
        timeAgoString =
            [NSString stringWithFormat:@"%i month ago", [comps month]];
    }
    else if ([comps day] > 0) {
        timeAgoString =
            [NSString stringWithFormat:@"%i days ago", [comps day]];
    }
    else if ([comps hour] > 0) {
        timeAgoString =
            [NSString stringWithFormat:@"%i hours ago", [comps hour]];
    }
    else if ([comps minute] > 0) {
        timeAgoString =
            [NSString stringWithFormat:@"%i mins ago", [comps minute]];
    }
    else if ([comps second] > 0) {
        timeAgoString =
            [NSString stringWithFormat:@"%i secs ago", [comps second]];
    }
    return timeAgoString;
}
Share and Enjoy:
  • Print
  • StumbleUpon
  • Facebook
  • Twitter
  • Google Bookmarks

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>