我想在不同日期将当前时间与两个不同的时间进行比较。我的代码是
NSString *time1 = record.trigger_from_time;
NSString *time2 = record.trigger_to_time;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSLog(@"%@,%@",date1,date2);
我的日志记录为2000-01-01 09:12:00 + 0000,2000-01-01 12:30:00 +0000
但我现在的时间是2014-04-01 17:06:18。
我从
获取当前日期NSDate *now = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
timeFormatter.dateFormat = @"HH:mm";
[timeFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(@"The Current Time is %@",[timeFormatter stringFromDate:now]);
我想将当前时间与record.trigger_from_time和record.trigger_to_time进行比较
答案 0 :(得分:2)
NSString *time1 = @"09:10:02";
NSString *time2 = @"17:10:16";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:"];
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSComparisonResult result = [date1 compare:date2];
if(result == NSOrderedDescending)
{
NSLog(@"time1 is later than time2");
}
else if(result == NSOrderedAscending)
{
NSLog(@"time2 is later than time1");
}
else
{
NSLog(@"time1 is equal to time2");
}
答案 1 :(得分:1)
比较2个NSDates。
...
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
if ([date2 compare:date1] == NSOrderedDescending) {
NSLog(@"date1 is later than date2");
} else if ([date2 compare:date1] == NSOrderedAscending) {
NSLog(@"date1 is earlier than date2");
} else {
NSLog(@"dates are the same");
}
UPD: 通过开关
...
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSComparisonResult result = [date2 compare:date1];
switch(result){
case NSOrderedDescending:
NSLog(@"date1 is later than date2");
break;
case NSOrderedAscending:
NSLog(@"date1 is earlier than date2");
break;
default:
NSLog(@"dates are the same");
break;
}