【发布时间】:2011-09-09 07:19:40
【问题描述】:
我想比较两个日期:date1 和 date2
2011-06-06 12:59:48.994 Project[419:707] firstDate:2011-06-06 10:59:21 +0000
2011-06-06 12:59:49.004 Project[419:707] selectedData:2011-06-06 10:59:17 +0000
但是这些日期有不同的时间,当我使用 NSOrderedSame 时它不能正常工作,我该如何解决?
我的代码:
NSDate *firstDate = [[appDelegate.project objectAtIndex:i]objectAtIndex:3];
NSDate *secondDate = [[appDelegate.project objectAtIndex:i]objectAtIndex:4];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);
NSDateComponents *date1Components = [calendar components:comps
fromDate:firstDate];
NSDateComponents *date2Components = [calendar components:comps
fromDate:secondDate];
NSDateComponents *date3Components = [calendar components:comps fromDate:appDelegate.selectedDate];
NSLog(@"firstDate:%@", [date1Components date]);
NSLog(@"secondDate:%@", [date2Components date]);
NSLog(@"selectedData:%@", [date3Components date]);
NSComparisonResult compareStart = [[date1Components date] compare: [date3Components date]];
NSComparisonResult compareEnd = [[date2Components date] compare: [date3Components date]];
if ((compareStart == NSOrderedAscending || compareStart == NSOrderedSame)
&& (compareEnd == NSOrderedDescending || compareEnd == NSOrderedSame))
{
NSLog(@"inside");
然后我想在 date1
【问题讨论】:
-
代替
NSLog(@"firstDate:%@", [date1Components date]);试试NSLog(@"firstDate:%@", [calendar dateFromComponents:date1Components]);有什么变化吗? -
现在是 2011-06-05 22:00:00 +0000 为什么?????
-
可能是一些时区/夏令时魔法
-
一切正常:我写 [date1Components setTimeZone:[ NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ] ;和 NSComparisonResult compareStart = [[calendar dateFromComponents:date1Components] compare: [calendar dateFromComponents:date3Components]];谢谢...
标签: objective-c ios cocoa-touch nsdate