比较三个日期

时间:2014-04-10 21:58:01

标签: objective-c nsdate

我有三个日期' startDate',stopDatecurrentDate。我需要比较" startDate' < =' currentDate'并且' stopDate' > =' currentDate'。我的代码。

unsigned int flagsDate = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;

    NSDateComponents* fromComponents = [[NSCalendar currentCalendar] components:flagsDate fromDate:startDate];
    NSDate* fromDateOnly = [[NSCalendar currentCalendar] dateFromComponents:fromComponents];

    NSDateComponents* toComponents = [[NSCalendar currentCalendar] components:flagsDate fromDate:stopDate];
    NSDate* toDateOnly = [[NSCalendar currentCalendar] dateFromComponents:toComponents];

    NSDate * currentDate = [NSDate date];
    NSDateComponents* currComponents = [[NSCalendar currentCalendar] components:flagsDate fromDate: currentDate];
    NSDate* currDateOnly = [[NSCalendar currentCalendar] dateFromComponents:currComponents];

    NSTimeInterval fromTime = [fromDateOnly timeIntervalSinceReferenceDate];
    NSTimeInterval toTime = [toDateOnly timeIntervalSinceReferenceDate];
    NSTimeInterval currTime = [currDateOnly timeIntervalSinceReferenceDate];

    NSLog(@"%@ %@",currentDate, currDateOnly);
    NSLog(@"%@ %@",startDate, fromDateOnly);
    NSLog(@"%@ %@",stopDate, toDateOnly);

带来nslog的是什么。

2014-04-10 23:59:53.280 Calendar [2148:90b] 2014-04-10 19:59:53 +0000 2014-04-09 20:00:00 +0000 2014-04-10 23:59:53.282日历[2148:90b] 2014-04-10 20:14:12 +0000 2014-04-10 20:00:00 +0000 2014-04-10 23:59:53.282日历[2148:90b] 2015-04-09 20:14:12 +0000 2015-04-09 20:00:00 +0000

如何比较日期?我需要在没有时间的情况下比较日期。如果时间少于20:00,为什么要更改日期?

3 个答案:

答案 0 :(得分:1)

NSTimeInterval distanceBetweenDates = [StartDate timeIntervalSinceDate:EndDate];

if (distanceBetweenDates > 0) {
    NSLog("Greather than ")
} else  if (distanceBetweenDates < 0) {
    NSLog("less than");
} else {
    NSLog("Equal");
}

答案 1 :(得分:0)

Alexey,我建议你在项目中加入这个精彩的NSDate扩展:https://github.com/erica/NSDate-Extensions

然后您可以使用

- (NSInteger)distanceInDaysToDate:(NSDate *)anotherDate

并检查它是否&lt; 0,0或&gt; 0

答案 2 :(得分:0)

如果您只想比较日期,请执行以下操作:

NSInteger flagsDate = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);

NSDateComponents* fromComponents = [[NSCalendar currentCalendar] components:flagsDate fromDate:startDate];
NSDateComponents* toComponents = [[NSCalendar currentCalendar] components:flagsDate fromDate:stopDate];
NSDateComponents* currComponents = [[NSCalendar currentCalendar] components:flagsDate fromDate:cu];

NSComparisonResult firstComparison = [[fromComponents date] compare: [currComponents date]]; 
NSComparisonResult secondComparison = [[toComponents date] compare: [currComponents date]]; 

然后检查你的结果

if (firstComparison == NSOrderedDescending || firstComparison == NSOrderedSame) {}
if (secondComparison == NSOrderedSame || secondComparison == NSOrderedAscending) {}