Friday, May 10, 2013

NSDateFormatter setLenient example ios


setLenient:

Sets whether the receiver uses heuristics when parsing a string.
- (void)setLenient:(BOOL)b
Parameters
b
YES to use heuristics when parsing a string to guess at the date which is intended, otherwiseNO.
Discussion of [NSDateFormatter setLenient]
If a formatter is set to be lenient, when parsing a string it uses heuristics to guess at the date which is intended. As with any guessing, it may get the result date wrong (that is, a date other than that which was intended).
Example of [NSDateFormatter setLenient]
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setLenient:YES];

NSDate * date = [formatter dateFromString:@"01-01/2001"];

NSLog(@"%@", date);
Example of [NSDateFormatter setLenient]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH-mm"];
[formatter setLenient:YES];

NSLog(@"Format: %@",[formatter dateFormat]);

[formatter release];
Example of [NSDateFormatter setLenient]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH-mm"];
[formatter setLenient:YES];
NSDate *time = [formatter dateFromString:[textbox text]];
[formatter release];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:NSYearCalendarUnit |
                                               NSMonthCalendarUnit |
                                               NSDayCalendarUnit |
                                               NSHourCalendarUnit |
                                               NSMinuteCalendarUnit
                                      fromDate:[NSDate date]];
NSDateComponents *timeComps = [calendar components:NSHourCalendarUnit |
                                                   NSMinuteCalendarUnit
                                          fromDate:time];

[comps setHour:[timeComps hour]];
[comps setMinute:[timeComps minute]];
NSDate *date = [calendar dateFromComponents:comps];
NSLog(@"Date from textfield: %@",date);