iOS:比较两个日期

Cra*_*Dev 96 objective-c nsdate ios

我有一个NSDate,我必须和另外两个比较NSDate,我试着用NSOrderAscendingNSOrderDescending,但如果我的日期是在其他两个日期平等吗?

示例:如果我有一个myDate = 24/05/2011 和另外两个是一个= 24/05/2011和两个24/05/2011我可以使用什么?

Vin*_*rci 210

根据Apple的文档NSDate compare:

返回NSComparisonResult值,该值指示接收方的时间顺序和另一个给定日期.

- (NSComparisonResult)compare:(NSDate *)anotherDate

参数 anotherDate

比较接收器的日期.该值不得为零.如果值为nil,则行为未定义,并且可能在将来的Mac OS X版本中更改.

回报价值

如果:

接收器和另一个日期彼此完全相同, NSOrderedSame

接收器的时间晚于另一个日期, NSOrderedDescending

接收器比另一个日期更早, NSOrderedAscending

换一种说法:

if ([date1 compare:date2] == NSOrderedSame) ...
Run Code Online (Sandbox Code Playgroud)

请注意,在您的特定情况下,读取和写入此内容可能更容易:

if ([date2 isEqualToDate:date2]) ...
Run Code Online (Sandbox Code Playgroud)

有关此文档,请参阅Apple文档.


Yos*_*far 32

在搜索了stackoverflow和web之后,我必须得出结论,最好的方法就是这样:

- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
    NSDate* enddate = checkEndDate;
    NSDate* currentdate = [NSDate date];
    NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
    double secondsInMinute = 60;
    NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;

    if (secondsBetweenDates == 0)
        return YES;
    else if (secondsBetweenDates < 0)
        return YES;
    else
        return NO;
}
Run Code Online (Sandbox Code Playgroud)

您也可以将其更改为小时数之间的差异.

请享用!


编辑1

如果您只想将日期与dd/MM/yyyy的格式进行比较,则需要在NSDate* currentdate = [NSDate date];&& 之间添加以下行NSTimeInterval distance

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                          autorelease]];

NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

currentdate = [dateFormatter dateFromString:stringDate];
Run Code Online (Sandbox Code Playgroud)


Him*_*ury 23

我认为你在询问比较函数中的返回值是什么.

如果日期相等则返回 NSOrderedSame

如果升序(第二个arg> 1st arg)返回 NSOrderedAscending

如果下降(第二个arg <1st arg)返回 NSOrderedDescending


Mat*_*uch 16

我不确切地知道您是否已经问过这个问题,但如果您只想比较NSDate的日期组件,则必须使用NSCalendar和NSDateComponents来删除时间组件.

像这样的东西应该作为NSDate的一个类别:

- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];

    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
    return [selfDateOnly compare:otherDateOnly];
}
Run Code Online (Sandbox Code Playgroud)