Return to Snippet

Revision: 70417
at February 6, 2016 17:22 by dipenpatel


Initial Code
- (NSString *)relativeDateStringForDate:(NSDate *)date
{
   NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfYear | 
                          NSCalendarUnitMonth | NSCalendarUnitYear;

   // if `date` is before "now" (i.e. in the past) then the components will be positive
   NSDateComponents *components = [[NSCalendar currentCalendar] components:units
                                                                  fromDate:date
                                                                    toDate:[NSDate date]
                                                                   options:0];

    if (components.year > 0) {
       return [NSString stringWithFormat:@"%ld years ago", (long)components.year];
   } else if (components.month > 0) {
       return [NSString stringWithFormat:@"%ld months ago", (long)components.month];
   } else if (components.weekOfYear > 0) {
       return [NSString stringWithFormat:@"%ld weeks ago", (long)components.weekOfYear];
   } else if (components.day > 0) {
       if (components.day > 1) {
           return [NSString stringWithFormat:@"%ld days ago", (long)components.day];
       } else {
           return @"Yesterday";
       }
   } else {
       return @"Today";
    }
}

Initial URL
http://apptraitsolutions.com

Initial Description
This snippet is used to covert any date to days like today, tomorrow, 2 days ago, 2 weeks ago or even 1 years ago.

Initial Title
Display date as Today, Tomorrow, 2 Days ago etc

Initial Tags
iphone, ios

Initial Language
Objective C