Reputation: 101
I have two strings with the format as Fri, 22 Jan 2016 10:46:50 +0530. I need to compare these two strings.If it can be done by converting them to date ,how can i write that NSDateFormatter style. Tried the code below. but not working. I'm getting the newDate and currentDate as nil. Any help would be appreciated.
NSString *dateString1 = @"Fri, 22 Jan 2016 10:46:50 +0530";
NSString *dateString2 = @"Fri, 21 Jan 2016 10:46:50 +0530";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateStyle:NSDateFormatterFullStyle];
NSDate *newDate = [inputFormatter dateFromString:dateString1];
NSDate *currentDate = [inputFormatter dateFromString:dateString2];
[inputFormatter release];
NSComparisonResult result = [newDate compare:currentDate]; // comparing two dates
if(result == NSOrderedAscending || result == NSOrderedSame) {
NSLog(@"newDate is less or same");
}
Upvotes: 0
Views: 1454
Reputation: 3089
Use [inputFormatter setDateFormat:@"EEE, DD MMM yyyy HH:mm:ss z"];
NSString *dateString1 = @"Fri, 22 Jan 2016 10:46:50 +0530";
NSString *dateString2 = @"Fri, 22 Jan 2016 10:46:50 +0530";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
NSDate *newDate = [inputFormatter dateFromString:dateString1];
NSDate *currentDate = [inputFormatter dateFromString:dateString2];
NSComparisonResult result = [newDate compare:currentDate]; // comparing two dates
if(result == NSOrderedAscending || result == NSOrderedSame) {
NSLog(@"newDate is less or same");
}
Upvotes: 7
Reputation: 82769
set dateformat like
if your time format is 12 hour - use hh
else if your time format is 24 hour use - HH
NSString *dateString1 = @"Fri, 22 Jan 2016 10:46:50 +0530";
[inputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
if you are using ARC no need of this [inputFormatter release];
Upvotes: 3