Friday, May 10, 2013

NSDateFormatter setFormatterBehavior example ios


setFormatterBehavior:

Sets the formatter behavior for the receiver.
- (void)setFormatterBehavior:(NSDateFormatterBehavior)behavior
Parameters
behavior
The formatter behavior for the receiver. For possible values, seeNSDateFormatterBehavior.


Example of [NSDateFormatter setFormatterBehavior]

NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setFormatterBehavior:NSDateFormatterBehaviorDefault];

NSDate *theDate = [df dateFromString:@"2011-04-12 10:00:00"];
NSLog(@"date: %@", theDate);

Example of [NSDateFormatter setFormatterBehavior]
for (int k = 0; k<[dateArray count]; k++)  
 {
    NSString *dateStr = [dateArray objectAtIndex:k];
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
    [dateFormatter1 setFormatterBehavior:NSDateFormatterBehaviorDefault];
    [dateFormatter1 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSLog(@"DateStr : %@", dateStr); //Console Output is : 2012-07-09 13:50:07 [For 42nd and above values]
    NSDate *date = [dateFormatter1 dateFromString:dateStr];
    NSLog(@"Date : %@", date); // Console Output is : (null) [For 42nd and above values]
 }
Example of [NSDateFormatter setFormatterBehavior]
NSDate *date = [NSDate date];
NSDateFormatter *prefixDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[prefixDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[prefixDateFormatter setDateFormat:@"h:mm a EEEE MMMM d"];
NSString *prefixDateString = [prefixDateFormatter stringFromDate:date];
NSDateFormatter *monthDayFormatter = [[[NSDateFormatter alloc] init] autorelease];
[monthDayFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[monthDayFormatter setDateFormat:@"d"];  
int date_day = [[monthDayFormatter stringFromDate:date] intValue]; 
NSString *suffix_string = @"|st|nd|rd|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|st|nd|rd|th|th|th|th|th|th|th|st";
NSArray *suffixes = [suffix_string componentsSeparatedByString: @"|"];
NSString *suffix = [suffixes objectAtIndex:date_day]; 
NSString *dateString = [prefixDateString stringByAppendingString:suffix]; 
NSLog(@"%@", dateString);