Friday, May 10, 2013

NSDateFormatter doesRelativeDateFormatting example ios


doesRelativeDateFormatting

Returns a Boolean value that indicates whether the receiver uses phrases such as “today” and “tomorrow” for the date component.
- (BOOL)doesRelativeDateFormatting
Return Value
YES if the receiver uses relative date formatting, otherwise NO.
Discussion
For a full discussion, see setDoesRelativeDateFormatting:.
Example of [NSDateFormatter doesRelativeDateFormatting]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.doesRelativeDateFormatting = YES;
Example of [NSDateFormatter doesRelativeDateFormatting]
NSLocale *locale = [NSLocale currentLocale];
//    NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];

NSDateFormatter *relativeDateFormatter = [[NSDateFormatter alloc] init];
[relativeDateFormatter setTimeStyle:NSDateFormatterNoStyle];
[relativeDateFormatter setDateStyle:NSDateFormatterMediumStyle];
[relativeDateFormatter setDoesRelativeDateFormatting:YES];
[relativeDateFormatter setLocale:locale];

NSDateFormatter *normalDateFormatter = [[NSDateFormatter alloc] init];
[normalDateFormatter setTimeStyle:NSDateFormatterNoStyle];
[normalDateFormatter setDateStyle:NSDateFormatterMediumStyle];
[normalDateFormatter setDoesRelativeDateFormatting:NO];
[normalDateFormatter setLocale:locale];

NSString * lastUniqueString = nil;

for ( NSTimeInterval timeInterval = -60*60*24*400; timeInterval < 60*60*24*400; timeInterval += 60.0*60.0*24.0 )
{
    NSDate * date = [NSDate dateWithTimeIntervalSinceNow:timeInterval];

    NSString * relativeFormattedString = [relativeDateFormatter stringForObjectValue:date];
    NSString * formattedString = [normalDateFormatter stringForObjectValue:date];

    if ( [relativeFormattedString isEqualToString:lastUniqueString] || [relativeFormattedString isEqualToString:formattedString] )
        continue;

    NSLog( @"%@", relativeFormattedString );
    lastUniqueString = relativeFormattedString;
}
Example of [NSDateFormatter doesRelativeDateFormatting]
NSDateFormatter *dateFormatter = NSDateFormatter.new;
dateFormatter.doesRelativeDateFormatting = YES;
dateFormatter.dateStyle = NSDateFormatterShortStyle;
dateFormatter.timeStyle = NSDateFormatterShortStyle;

NSDate *today = NSDate.new;
// "Today, 11:40 AM"
NSLog(@"%@", [dateFormatter stringFromDate:today]);

NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:60*60*24];
// "Tomorrow, 11:40 AM"
NSLog(@"%@", [dateFormatter stringFromDate:tomorrow]);

NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-(60*60*24)];
// "Yesterday, 11:40 AM"
NSLog(@"%@", [dateFormatter stringFromDate:yesterday]);

NSDate *dayAfter = [NSDate dateWithTimeIntervalSinceNow:(60*60*24)*2];
// "2/14/13, 11:40 AM"
NSLog(@"%@", [dateFormatter stringFromDate:dayAfter]);