Friday, May 10, 2013

NSDateFormatter setDoesRelativeDateFormatting example ios


Specifies whether the receiver uses phrases such as “today” and “tomorrow” for the date component.
- (void)setDoesRelativeDateFormatting:(BOOL)b
YES to specify that the receiver should use relative date formatting, otherwise NO.
Discussion of [NSDateFormatter setDoesRelativeDateFormatting]
If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as “today” or “tomorrow”—that indicates a relative date. The available phrases depend on the locale for the date formatter; whereas, for dates in the future, English may only allow “tomorrow,” French may allow “the day after the day after tomorrow,” as illustrated in the following example.
Example of [NSDateFormatter setDoesRelativeDateFormatting]

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
[dateFormatter setLocale:frLocale];
[dateFormatter setDoesRelativeDateFormatting :YES];
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3];
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(@"dateString: %@", dateString);
// Output
// dateString: après-après-demain

Example of [NSDateFormatter setDoesRelativeDateFormatting]

-(NSString*) airDay 
    NSDateFormatter *dayFormatter=[[NSDateFormatter alloc] init];
   [dayFormatter setLocale:[NSLocale currentLocale]];
   [dayFormatter setDateStyle: NSDateFormatterMediumStyle];
   [dayFormatter setDoesRelativeDateFormatting: YES];  

   return [dayFormatter stringFromDate:self.startDate];

Example of [NSDateFormatter setDoesRelativeDateFormatting]
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])

    @autoreleasepool {

        NSDateFormatter * formatter = [[NSDateFormatter  alloc] init];
        [formatter setDateStyle:NSDateFormatterFullStyle];
        [formatter setDoesRelativeDateFormatting:YES];

        NSCalendar * cal = [[NSLocale currentLocale] objectForKey:NSLocaleCalendar];
        NSDateComponents * minusOneDay = [[NSDateComponents alloc] init];
        [minusOneDay setDay:-1];
        NSDate * today = [NSDate date];
        NSDate * date = [NSDate date];

        while( 1 > [[cal components:NSYearCalendarUnit fromDate:date toDate:today options:0] year] ){

            NSLog(@"%@", [formatter stringFromDate:date]);
            date = [cal dateByAddingComponents:minusOneDay

    return 0;