objective-c 如何在Objective-C中比较两个日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/949416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:39:55  来源:igfitidea点击:

How to compare two dates in Objective-C

objective-ccocoadatedate-comparison

提问by Raju

I have two dates: 2009-05-11and the current date. I want to check whether the given date is the current date or not. How is this possible.

我有两个日期:2009-05-11和当前日期。我想检查给定的日期是否是当前日期。这怎么可能。

回答by stefanB

Cocoa has couple of methods for this:

Cocoa 有两种方法

in NSDate

在 NSDate

– isEqualToDate:  
– earlierDate:  
– laterDate:  
– compare:

When you use - (NSComparisonResult)compare:(NSDate *)anotherDate,you get back one of these:

当你使用时- (NSComparisonResult)compare:(NSDate *)anotherDate,你会得到以下之一:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame
The receiver is later in time than anotherDate, NSOrderedDescending
The receiver is earlier in time than anotherDate, NSOrderedAscending.

example:

例子:

NSDate * now = [NSDate date];
NSDate * mile = [[NSDate alloc] initWithString:@"2001-03-24 10:45:32 +0600"];
NSComparisonResult result = [now compare:mile];

NSLog(@"%@", now);
NSLog(@"%@", mile);

switch (result)
{
    case NSOrderedAscending: NSLog(@"%@ is in future from %@", mile, now); break;
    case NSOrderedDescending: NSLog(@"%@ is in past from %@", mile, now); break;
    case NSOrderedSame: NSLog(@"%@ is the same as %@", mile, now); break;
    default: NSLog(@"erorr dates %@, %@", mile, now); break;
}

[mile release];

回答by Naveed Rafi

Here buddy. This function will match your date with any specific date and will be able to tell whether they match or not. You can also modify the components to match your requirements.

这里哥们。此功能会将您的日期与任何特定日期进行匹配,并能够判断它们是否匹配。您还可以修改组件以满足您的要求。

- (BOOL)isSameDay:(NSDate*)date1 otherDay:(NSDate*)date2 {
NSCalendar* calendar = [NSCalendar currentCalendar];

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];

return [comp1 day]   == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year]  == [comp2 year];}

Regards, Naveed Butt

问候, Naveed Butt

回答by Sajjad

NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [NSDate dateWithString:@"xxxxxx"]; // your date 

NSComparisonResult result; 
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending

result = [today compare:newDate]; // comparing two dates

if(result==NSOrderedAscending)
    NSLog(@"today is less");
else if(result==NSOrderedDescending)
    NSLog(@"newDate is less");
else
    NSLog(@"Both dates are same");

There are other ways that you may use to compare an NSDate objects. Each of the methods will be more efficient at certain tasks. I have chosen the compare method because it will handle most of your basic date comparison needs.

还有其他方法可以用来比较 NSDate 对象。每种方法在某些任务上都会更有效。我选择了比较方法,因为它可以处理您的大部分基本日期比较需求。

回答by Pascal

Thiscategory offers a neat way to compare NSDates:

这个类别提供了一种比较 NSDates 的巧妙方法:

#import <Foundation/Foundation.h>

@interface NSDate (Compare)

-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
//- (BOOL)isEqualToDate:(NSDate *)date; already part of the NSDate API

@end

And the implementation:

和实施:

#import "NSDate+Compare.h"

@implementation NSDate (Compare)

-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
    return !([self compare:date] == NSOrderedAscending);
}

-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
    return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
    return ([self compare:date] == NSOrderedDescending);

}
-(BOOL) isEarlierThan:(NSDate*)date {
    return ([self compare:date] == NSOrderedAscending);
}

@end

Simple to use:

使用简单:

if([aDateYouWantToCompare isEarlierThanOrEqualTo:[NSDate date]]) // [NSDate date] is now
{
    // do your thing ...
}

回答by Alex Rozanski

If you make both dates NSDates you can use NSDate's compare:method:

如果您同时创建两个日期NSDate,则可以使用NSDate'scompare:方法:

NSComparisonResult result = [Date2 compare:Date1];

if(result==NSOrderedAscending)
    NSLog(@"Date1 is in the future");
else if(result==NSOrderedDescending)
    NSLog(@"Date1 is in the past");
else
    NSLog(@"Both dates are the same");

You can take a look at the docs here.

您可以在此处查看文档。

回答by kapil

By this method also you can compare two dates

通过这种方法,您也可以比较两个日期

NSDate * dateOne = [NSDate date];
NSDate * dateTwo = [NSDate date];

if([dateOne compare:dateTwo] == NSOrderedAscending)
{

}

回答by Chei

The best way I found was to check the difference between the given date and today:

我发现的最好方法是检查给定日期和今天之间的差异:

NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* now = [NSDate date];
int differenceInDays =
[calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:date] -
[calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:now];

According to Listing 13 of Calendrical Calculationsin Apple's Date and Time Programming Guide[NSCalendar ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:myDate] gives you the number of midnights since the start of the era. This way it's easy to check whether the date is yesterday, today, or tomorrow.

根据Apple 的日期和时间编程指南中日历计算清单 13 [NSCalendar ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:myDate] 为您提供自时代开始以来的午夜数。这样就很容易检查日期是昨天、今天还是明天。

switch (differenceInDays) {
    case -1:
        dayString = @"Yesterday";
        break;
    case 0:
        dayString = @"Today";
        break;
    case 1:
        dayString = @"Tomorrow";
        break;
    default: {
        NSDateFormatter* dayFormatter = [[NSDateFormatter alloc] init];
        [dayFormatter setLocale:usLocale];
        [dayFormatter setDateFormat:@"dd MMM"];
        dayString = [dayFormatter stringFromDate: date];
        break;
    }
}

回答by iphonedev23

NSDateFormatter *df= [[NSDateFormatter alloc] init];

[df setDateFormat:@"yyyy-MM-dd"];

NSDate *dt1 = [[NSDate alloc] init];

NSDate *dt2 = [[NSDate alloc] init];

dt1=[df dateFromString:@"2011-02-25"];

dt2=[df dateFromString:@"2011-03-25"];

NSComparisonResult result = [dt1 compare:dt2];

switch (result)
{

        case NSOrderedAscending: NSLog(@"%@ is greater than %@", dt2, dt1); break;

        case NSOrderedDescending: NSLog(@"%@ is less %@", dt2, dt1); break;

        case NSOrderedSame: NSLog(@"%@ is equal to %@", dt2, dt1); break;

        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;

}

Enjoy coding......

享受编码......

回答by Suvesh Pratapa

In Cocoa, to compare dates, use one of isEqualToDate, compare, laterDate, and earlierDatemethods on NSDateobjects, instantiated with the dates you need.

在可可,比较日期,使用一个isEqualToDatecomparelaterDate,和earlierDate方法的NSDate对象,你需要的日期实例化。

Documentation:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/isEqualToDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/earlierDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/laterDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/compare:

文档:
http:
//developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/isEqualToDatehttp: //developer.apple。 com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/earlierDate:
http : //developer.apple.com/documentation/Cocoa/Reference/Foundation/ Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/laterDate:http :
//developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html# //apple_ref/occ/instm/NSDate/compare:

回答by David Salzer

What you really need is to compare two objects of the same kind.

您真正需要的是比较两个相同类型的对象。

  1. Create an NSDate out of your string date (@"2009-05-11") :
    http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html

  2. If the current date is a string too, make it an NSDate. If its already an NSDate, leave it.

  1. 从字符串日期(@“2009-05-11”)中创建一个 NSDate :
    http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html

  2. 如果当前日期也是字符串,请将其设为 NSDate。如果它已经是一个 NSDate,就离开它。