如何比较两次从NSDate。 在比较时返回ndate。 #debug我的代码

这里是代码:

// get current date/time NSDate *today = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // display in 12HR/24HR (ie 11:25PM or 23:25) format according to User Settings [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; [dateFormatter setDateFormat:@"HH:mm:ss"]; NSString *currentTime = [dateFormatter stringFromDate:today]; currentTime = [currentTime stringByReplacingOccurrencesOfString:@"AM" withString:@""]; currentTime = [currentTime stringByReplacingOccurrencesOfString:@"PM" withString:@""]; currentTime = [currentTime stringByReplacingOccurrencesOfString:@" " withString:@""]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setTimeStyle:NSDateFormatterMediumStyle]; [formatter setDateFormat:@"HH:mm:ss"]; NSDate *date1= [formatter dateFromString:currentTime]; NSDate *date2 = [formatter dateFromString:@"5:00:00"]; NSComparisonResult result = [date1 compare:date2]; if(result == NSOrderedDescending) { NSLog(@"date1 is later than date2"); } 

在这里,当我运行代码时,我将date1和date2设置为nil,而我正确地以24小时格式获取当前时间。 我从[NSDate date]获取当前时间的同一date格式。 我在这里错过了什么?

编辑1:修正了错字,改变了标题。

编辑2:根据build议,比较只有我可以使用的小时:

 NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [calendar components:(NSHourCalendarUnit) fromDate:date1]; NSInteger hour = [components hour]; 

编辑3:改变标题,以符合确切的要求。

但我不能从当前时间检索date1。 它抛出一个垃圾值。

有一个错字:
[dateFormatter setDateFormat:@"HH:mm:ss"];
应该:
[formatter setDateFormat:@"HH:mm:ss"];

要比较两个date使用:

 NSDate *date1 = [NSDate date]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"HH:mm:ss"]; NSDate *date2 = [formatter dateFromString:@"05:00:00"]; NSComparisonResult result = [date1 compare:date2]; if(result == NSOrderedDescending) { NSLog(@"date1 is later than date2"); } 

如果你只想比较几个小时:

 NSCalendar *calendar = [NSCalendar currentCalendar]; NSDate *date1 = [NSDate date]; NSDateComponents *date1Components = [calendar components:NSCalendarUnitHour fromDate:date1]; NSInteger date1Hour = date1Components.hour; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"HH:mm:ss"]; NSDate *date2 = [formatter dateFromString:@"05:00:00"]; NSDateComponents *date2Components = [calendar components:NSCalendarUnitHour fromDate:date2]; NSInteger date2Hour = date2Components.hour; if(date1Hour > date2Hour) { NSLog(@"date1 is later than date2"); }