Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In the interest of completeness, based on a @Gilean's answer, here's the complete code for a simple category on NSDate that mimics rails' nifty date helpers. For a refresher on categories, these are instance methods that you would call on NSDate objects. So, if I have an NSDate that represents yesterday, [myDate distanceOfTimeInWordsToNow] => "1 day".</p> <p>Hope it's useful!</p> <pre><code>@interface NSDate (NSDate_Relativity) -(NSString *)distanceOfTimeInWordsSinceDate:(NSDate *)aDate; -(NSString *)distanceOfTimeInWordsToNow; @end @implementation NSDate (NSDate_Relativity) -(NSString *)distanceOfTimeInWordsToNow { return [self distanceOfTimeInWordsSinceDate:[NSDate date]]; } -(NSString *)distanceOfTimeInWordsSinceDate:(NSDate *)aDate { double interval = [self timeIntervalSinceDate:aDate]; NSString *timeUnit; int timeValue; if (interval &lt; 0) { interval = interval * -1; } if (interval&lt; 60) { return @"seconds"; } else if (interval&lt; 3600) { // minutes timeValue = round(interval / 60); if (timeValue == 1) { timeUnit = @"minute"; } else { timeUnit = @"minutes"; } } else if (interval&lt; 86400) { timeValue = round(interval / 60 / 60); if (timeValue == 1) { timeUnit = @"hour"; } else { timeUnit = @"hours"; } } else if (interval&lt; 2629743) { int days = round(interval / 60 / 60 / 24); if (days &lt; 7) { timeValue = days; if (timeValue == 1) { timeUnit = @"day"; } else { timeUnit = @"days"; } } else if (days &lt; 30) { int weeks = days / 7; timeValue = weeks; if (timeValue == 1) { timeUnit = @"week"; } else { timeUnit = @"weeks"; } } else if (days &lt; 365) { int months = days / 30; timeValue = months; if (timeValue == 1) { timeUnit = @"month"; } else { timeUnit = @"months"; } } else if (days &lt; 30000) { // this is roughly 82 years. After that, we'll say 'forever' int years = days / 365; timeValue = years; if (timeValue == 1) { timeUnit = @"year"; } else { timeUnit = @"years"; } } else { return @"forever ago"; } } return [NSString stringWithFormat:@"%d %@", timeValue, timeUnit]; } @end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload