Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 06-12-2011, 07:12 AM   #1 (permalink)
Registered Member
 
Join Date: Apr 2009
Posts: 118
lexy0202 is on a distinguished road
Default Date relative to now in string

Hi There,

Was wondering if anyone knew of a class which would give you a string telling you in 'human terms' how long ago a date was. For example on twitter/facebook when you see post dates like 2 minutes ago, or 3 hours ago, or 2 days ago... anyone know of a class which handles all the cases like this... or else how do I basically go about doing something like that with an NSDate??

Thanks in advance,
Alex
lexy0202 is offline   Reply With Quote
Old 06-12-2011, 07:25 AM   #2 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,003
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by lexy0202 View Post
Hi There,

Was wondering if anyone knew of a class which would give you a string telling you in 'human terms' how long ago a date was. For example on twitter/facebook when you see post dates like 2 minutes ago, or 3 hours ago, or 2 days ago... anyone know of a class which handles all the cases like this... or else how do I basically go about doing something like that with an NSDate??

Thanks in advance,
Alex
There's no single class to do this, but there are tools that make it fairly straightforward.

You need an NSCalendar object to define the calendar you're using. Most Western countries use the Gregorian calendar, so you probably want to create a gregorian calendar.

You could use the NSCalendar method components:fromDate:toDateptions. That will let you calculate a difference between dates using units you specify. The answer comes back and an NSDateComponents object, which gives you numbers of years, months, weeks, days, etc. You tell the components:fromDate:toDateptions method which units you want, and it calculates the answer in those units. There are then NSCalendar methods to convert NSDateComponents component values (months, days, years) to their string equivalents.

See the XCode docs on NSCalendar, NSDateComponents, and NSDate for more information. Its pretty well documented, and quite rich.

Edit: Make sure you search on "Calendrical Calculations" and read that whole chapter, and in particular the section titled "Temporal Differences". That section includes sample code that does almost exactly what you want.
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.

Last edited by Duncan C; 06-12-2011 at 07:48 AM.
Duncan C is offline   Reply With Quote
Old 06-12-2011, 08:01 AM   #3 (permalink)
Indie Developer
 
iSDK's Avatar
 
Join Date: Jul 2010
Posts: 1,346
iSDK is on a distinguished road
Send a message via AIM to iSDK
Default

Came across it a while ago on StackOverflow.

Code:
-(NSString *)dateDiff:(NSString *)origDate {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setFormatterBehavior:NSDateFormatterBehavior10_4];
    [df setDateFormat:@"EEE, dd MMM yy HH:mm:ss VVVV"];
    NSDate *convertedDate = [df dateFromString:origDate];
    [df release];
    NSDate *todayDate = [NSDate date];
    double ti = [convertedDate timeIntervalSinceDate:todayDate];
    ti = ti * -1;
    if(ti < 1) {
        return @"never";
    } else      if (ti < 60) {
        return @"less than a minute ago";
    } else if (ti < 3600) {
        int diff = round(ti / 60);
        return [NSString stringWithFormat:@"%d minutes ago", diff];
    } else if (ti < 86400) {
        int diff = round(ti / 60 / 60);
        return[NSString stringWithFormat:@"%d hours ago", diff];
    } else if (ti < 2629743) {
        int diff = round(ti / 60 / 60 / 24);
        return[NSString stringWithFormat:@"%d days ago", diff];
    } else {
        return @"never";
    }   
}
iSDK is offline   Reply With Quote
Old 06-12-2011, 08:51 AM   #4 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,003
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by iSDK View Post
Came across it a while ago on StackOverflow.

Code:
-(NSString *)dateDiff:(NSString *)origDate {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setFormatterBehavior:NSDateFormatterBehavior10_4];
    [df setDateFormat:@"EEE, dd MMM yy HH:mm:ss VVVV"];
    NSDate *convertedDate = [df dateFromString:origDate];
    [df release];
    NSDate *todayDate = [NSDate date];
    double ti = [convertedDate timeIntervalSinceDate:todayDate];
    ti = ti * -1;
    if(ti < 1) {
        return @"never";
    } else      if (ti < 60) {
        return @"less than a minute ago";
    } else if (ti < 3600) {
        int diff = round(ti / 60);
        return [NSString stringWithFormat:@"%d minutes ago", diff];
    } else if (ti < 86400) {
        int diff = round(ti / 60 / 60);
        return[NSString stringWithFormat:@"%d hours ago", diff];
    } else if (ti < 2629743) {
        int diff = round(ti / 60 / 60 / 24);
        return[NSString stringWithFormat:@"%d days ago", diff];
    } else {
        return @"never";
    }   
}

The code from Apple's documentation is simpler and more flexible:

Code:
NSDate *startDate = ...;
NSDate *endDate = ...;
 
NSCalendar *gregorian = [[NSCalendar alloc]
                 initWithCalendarIdentifier:NSGregorianCalendar];
 
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
 
NSDateComponents *components = [gregorian components:unitFlags
                                          fromDate:startDate
                                          toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
It depends on what the OP wants. Do you want the results in just one unit, or in a group of units? Also, what about other calendars like the Buddhist, Muslim, Hebrew, Chinese traditional, etc.? Apple's code will give good results for those calendars as well, if you just create the right calendar object.
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Reply

Bookmarks

Tags
date, nsdate, string, twitter

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 316
6 members and 310 guests
chemistry, Dnnake, iOS.Lover, lendo, Leslie80, pbart
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,664
Threads: 94,120
Posts: 402,898
Top Poster: BrianSlick (7,990)
Welcome to our newest member, Leslie80
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 02:22 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0