如何将两个给定时间与当前时间进行比较? [英] How to compare two given times with current time?
本文介绍了如何将两个给定时间与当前时间进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较不同日期的两个不同时间的当前时间。我的代码是
I want to compare current time with two different times on different dates.MY code is
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
I'm getting log as 2000-01-01 09:12:00 +0000,2000-01-01 12:30:00 +0000
但我现在的时间是2014-04-01 17:06:18。
But MY current time is 2014-04-01 17:06:18.
我从获得当前日期
I'm getting current date from
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
I want to compare thie current time with record.trigger_from_time and record.trigger_to_time
推荐答案
比较2个NSDates。
Comparing 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:
via Switch
UPD: via Switch
...
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;
}
这篇关于如何将两个给定时间与当前时间进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文