我想检查当前日期是否在两个给定日期之间。我执行以下操作
NSDate *now = [NSDate new];
NSLog(@"Now is %@",now);
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[components setYear:2013];
[components setMonth:06];
[components setDay:28];
[components setHour:5];
[components setMinute:00];
NSDate *startDate1 = [myCalendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone localTimeZone];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSLog(@"start dateeee is %@",startDate1);
NSDateComponents* components2 = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[components2 setYear:2013];
[components2 setMonth:06];
[components2 setDay:29];
[components2 setHour:4];
[components2 setMinute:59];
NSDate *endDate1 = [myCalendar dateFromComponents:components];
NSLog(@"end date is %@",endDate1)
;
现在我创建了 2 个日期Startdate1
和endDate1
. 为了检查当前日期是否在我正在执行的日期之间。
NSComparisonResult result1 = [now compare:startDate1];
NSComparisonResult result2 = [now compare:endDate1];
if (result2 == NSOrderedSame && result1 == NSOrderedSame ) {
NSLog(@"HELL YEAH! ");
}
但我从来没有得到一个地狱耶??
注意:我已将我的 iPhone 日期时间设置为开始日期和结束日期之间的时间。这里还有我的日志:
2013-06-29 11:11:48.727 Genk on stage[2205:907] Now is 2013-06-29 09:11:48 +0000
2013-06-29 11:11:48.728 Genk on stage[2205:907] start dateeee is 2013-06-28 03:00:00 +0000
2013-06-29 11:11:48.729 Genk on stage[2205:907] end date is 2013-06-28 03:00:00 +0000