如何比较两个日期和时间,EXP:07/10/2015 12:30至08/10/2015 02:00在ios中?
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
[timeFormatter setTimeZone:[NSTimeZone localTimeZone]];
[timeFormatter setDateFormat:@"dd/MM/YYYY HH:mm"];
NSDate *startDate = [timeFormatter1 dateFromString:@"07/10/2015 12:30"];
NSDate *EndDate = [timeFormatter1 dateFromString:@"08/10/2015 02:30"];
if([startDate compare:EndDate] == NSOrderedAscending)
return YES;
else
return NO;
我跟随上面的代码,但每次输出都是错误的结果(去“返回否”)。如何比较两个日期和时间,EXP:07/10/2015 12:30至08/10/2015 02:00在ios中?
同时EXP:07/10/2015 12:30到07/10/2015 23:30这是工作。
我需要在一个时间两种格式的工作。
请帮帮我吗?
的问题是在一年的格式。使用“yyyy”代替“YYYY”来解决问题。
这里的工作代码:
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
[timeFormatter setTimeZone:[NSTimeZone localTimeZone]];
[timeFormatter setDateFormat:@"dd/MM/yyyy HH:mm"];
NSDate *startDate = [timeFormatter dateFromString:@"07/10/2015 12:30"];
NSDate *EndDate = [timeFormatter dateFromString:@"08/10/2015 02:30"];
if([startDate compare:EndDate] == NSOrderedAscending)
NSLog(@"Ascending");
else
NSLog(@"Descending");
http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
检查此链接了解更多日期格式
谢谢@Gobi M,工作正常。 –
根据的NSDate的比较Apple Documentation:
返回一个NSComparisonResult值,指示接收器和其他特定日期的时间排序。
- (NSComparisonResult)compare:(NSDate *)anotherDate
参数anotherDate
的日期要与之比较的接收器。该值不能为零。如果该值是零,则行为是不确定的,并在Mac OS X的未来版本
返回值可以改变
如果:
接收器和anotherDate是完全相等,NSOrderedSame
接收机以后是在时间上比anotherDate,NSOrderedDescending
接收机较早在时间上比anotherDate,NSOrderedAscending 换句话说:
if ([date1 compare:date2] == NSOrderedSame) ...
注意,这可能是你的具体情况更容易阅读和写:
if ([date2 isEqualToDate:date2]) ...
我认为你错了'timeFormatter1'。可能你错过了'timeFormatter'。并且在startDate和EndDate中为零。 –