我有两个格式为Fri的字符串,2016年1月22日10:46:50 +0530。我需要比较这两个字符串。如果可以通过将它们转换为日期来完成,我该如何编写NSDateFormatter样式。试过下面的代码。但没有工作。我将newDate和currentDate设为nil。任何帮助将不胜感激。
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");
}
答案 0 :(得分:7)
使用[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");
}
答案 1 :(得分:3)
设置dateformat,如
如果您的时间格式是12小时 - 如果您的时间格式是24小时使用,则使用hh
其他 - HH
NSString *dateString1 = @"Fri, 22 Jan 2016 10:46:50 +0530";
[inputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
如果您使用ARC,则不需要此[inputFormatter release];