Подтвердить что ты не робот

Как сравнить две даты в Objective-C

У меня есть две даты: 2009-05-11 и текущая дата. Я хочу проверить, является ли данная дата текущей или нет. Как это возможно.

4b9b3361

Ответ 1

Cocoa имеет пару методов для этого:

в NSDate

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

Когда вы используете - (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.

Пример:

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];

Ответ 2

Вот приятель. Эта функция будет соответствовать вашей дате с любой указанной датой и будет сообщать о погоде, которую они соответствуют или нет. Вы также можете изменить компоненты в соответствии с вашими требованиями.

- (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];}

С уважением, Naveed Butt

Ответ 3

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");

Существуют и другие способы сравнения объектов NSDate. Каждый из методы будут более эффективными при выполнении определенных задач. Я выбрал метод сравнения потому что он будет обрабатывать большинство ваших основных потребностей сравнения даты.

Ответ 4

Эта категория предлагает опрятный способ сравнения 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

И реализация:

#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

Прост в использовании:

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

Ответ 5

С помощью этого метода вы также можете сравнить две даты

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

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

}

Ответ 6

Если вы делаете обе даты NSDate, вы можете использовать метод NSDate compare::

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");

Вы можете ознакомиться с документами здесь.

Ответ 7

Лучший способ, который я нашел, - проверить разницу между данной датой и сегодня:

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

Согласно листингу 13 Календарные вычисления в Apple Дата и Руководство по программированию времени [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;
    }
}

Ответ 8

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;

}

Наслаждайтесь кодированием......

Ответ 9

В Cocoa для сравнения дат используйте один из методов isEqualToDate, compare, laterDate и earlierDate на объектах NSDate, созданных с нужной датой.

Документация:
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:

Ответ 10

Вам действительно нужно сравнить два объекта одного и того же типа.

Ответ 11

Здесь вариант Swift на Pascal отвечает:

extension NSDate {

    func isLaterThanOrEqualTo(date:NSDate) -> Bool {
        return !(self.compare(date) == NSComparisonResult.OrderedAscending)
    }

    func isEarlierThanOrEqualTo(date:NSDate) -> Bool {
        return !(self.compare(date) == NSComparisonResult.OrderedDescending)
    }

    func isLaterThan(date:NSDate) -> Bool {
        return (self.compare(date) == NSComparisonResult.OrderedDescending)
    }

    func isEarlierThan(date:NSDate) -> Bool {
        return (self.compare(date) == NSComparisonResult.OrderedAscending)
    }
}

который может использоваться как:

self.expireDate.isEarlierThanOrEqualTo(NSDate())

Ответ 12

Здесь функция Naveed Rafi отвечает на преобразование в Swift, если кто-то ищет ее:

func isSameDate(#date1: NSDate, date2: NSDate) -> Bool {
    let calendar = NSCalendar()
    let date1comp = calendar.components(.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit, fromDate: date1)
    let date2comp = calendar.components(.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit, fromDate: date2)
    return (date1comp.year == date2comp.year) && (date1comp.month == date2comp.month) && (date1comp.day == date2comp.day)
}

Ответ 13

Get Today Date:

NSDate* date = [NSDate date];

Create a Date From Scratch:    
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.year = 2015;
comps.month = 12;
comps.day = 31;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* date = [calendar dateFromComponents:comps];


Add a day to a Date:  
NSDate* date = [NSDate date];
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = 1;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* tomorrow = [calendar dateByAddingComponents:comps toDate:date options:nil];


Subtract a day from a Date:    
NSDate* date = [NSDate date];
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = -1;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* yesterday = [calendar dateByAddingComponents:comps toDate:date options:nil];



Convert a Date to a String:  

NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSString* dateString = [formatter stringFromDate:date];


Convert a String to a Date:

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSDate* date = [formatter dateFromString:@"August 02, 2014"];


Find how many days are in a month:    
NSDate* date = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSRange currentRange = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger numberOfDays = currentRange.length;


Calculate how much time something took:   

NSDate* start = [NSDate date];
for(int i = 0; i < 1000000000; i++);
NSDate* end = [NSDate date];
NSTimeInterval duration = [end timeIntervalSinceDate:start];


Find the Day Of Week for a specific Date:

NSDate* date = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSInteger dow = [cal ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date];

Затем используйте NSComparisonResult для сравнения даты.

Ответ 14

..

NSString *date = @"2009-05-11"
NSString *nowDate = [[[NSDate date]description]substringToIndex: 10];
if([date isEqualToString: nowDate])
{
// your code
}