2009-06-04 12 views
60

Mam dwie daty: 2009-05-11 i bieżącą datę. Chcę sprawdzić, czy podana data jest aktualna, czy nie. Jak to jest możliwe.Jak porównać dwie daty w Objective-C

+0

Patrząc na odpowiedzi, nie jest jasne, czy chcesz dosłownie porównać dwie instancje NSDate dla równości (ten sam punkt w czasie), czy chcesz wiedzieć, czy są one w tym samym dniu kalendarzowym. –

Odpowiedz

2

To, czego naprawdę potrzebujesz, to porównać dwa obiekty tego samego rodzaju.

  1. Załóż NSDate z datą ciąg (@ "2009-05-11"):
    http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html

  2. Jeśli bieżąca data jest ciągiem też czynią go NSDate. Jeśli już jest NSDate, zostaw go.

+3

Nie można porównać dwóch obiektów, używając == – oxigen

+0

mój błąd, odpowiedział na inne pytanie w tym samym czasie. Dziękuję za komentarz. –

-2

..

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

Myślę, że o wiele bardziej użyteczne byłoby przekształcenie "daty" w obiekt NSDate, a następnie porównanie obiektów NSDate. Ten kod zadziała, ale substringToIndex: 10 to naprawdę hack. Jeśli potrzebujesz więcej informacji, np. Która data jest nowsza - musisz to zrobić w ten sposób. –

+0

Oczywiście można porównywać obiekty NSDate. Ale NSDate ma informacje o Dacie i Godzinie Twoje potrzeby 1. Utwórz NSDate ze stringa 2. Ponownie przesuń informacje z aktualnej daty na temat czasu (ustawiony czas do 00:00:00) I dopiero po tym porównać daty. Myślę, że ten sposób nie jest łatwy i szybki. – oxigen

+0

Jeśli jesteś zainteresowany tylko samym dniem, możesz utworzyć NSDate, a następnie użyć NSCalendar, aby wyprowadzić NSDateComponents z niego, w którym to momencie możesz porównywać wartości, które Cię interesują. Możesz również pobrać komponenty dla numeru dni od epoki, aby użyć go w jednym porównaniu. –

3
15

Jeśli się obie daty NSDate s można użyć NSDate „s compare: metody:

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

Można spojrzeć na dokumentach here.

151

Cocoa has couple of methods for this:

w NSDate

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

Podczas korzystania - (NSComparisonResult)compare:(NSDate *)anotherDate, wrócisz jednego z nich:

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. 

przykład:

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

W jaki sposób odpowiada to na pierwotne pytanie "czy dana data jest aktualna, czy nie"? [NSDate date] będzie NSOrderedSame na dowolny ustalony termin nie na 24 godziny, ale na mniej niż sekundę. – Chei

+0

To nie działa na iOS. Akceptowane odpowiedź na: http://stackoverflow.com/questions/14702626/no-visible-interface-for-nsdate-declares-the-selector-initwithstring –

+0

@HappyFlow pytanie jest oznaczone 'cocoa' nie wspomina iOS, aby uzyskać więcej informacji wypróbuj google "kakao" kontra "kakao dotyk" – stefanB

42

Tutaj kolego. Ta funkcja dopasuje twoją datę do określonej daty i powie, że pogoda będzie pasować. Możesz także modyfikować komponenty, aby pasowały do ​​twoich wymagań.

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

Pozdrawiam, Naveed Butt

+3

To jest poprawna odpowiedź. Chociaż górna odpowiedź może być bardziej ogólna, zapewnia to rozwiązanie specyficzne dla przedstawionego problemu. – elsurudo

+2

PO PROSTU IDEALNE !! Próbowałem kilka metod Stało HANDY – raghul

+2

Wielkie answer.Thanks – moujib

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

Istnieją inne sposoby, które można wykorzystać do porównywania obiektów NSDate. Każda z metod będzie bardziej wydajna przy niektórych zadaniach. Wybrałem metodę porównania , ponieważ zajmie się ona większością podstawowych potrzeb związanych z porównywaniem dat.

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

} 

Ciesz się kodowaniem ......

8

Najlepszym sposobem znalazłem sprawdzić różnicę między podaną datą i dziś:

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

Zgodnie z listą 13 z Calendrical Calculations w Apple Date and Time Programming Guide [NSCalendar ordinalityOfUnit: NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate: MyDate] daje Ty liczbę nocy od początku epoki. W ten sposób łatwo sprawdzić, czy data jest wczoraj, dziś czy jutro.

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; 
    } 
} 
28

This kategoria oferuje schludny sposób porównać 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 

i wdrożenie:

#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 

prosty w obsłudze:

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

dziękuję! Jest to o wiele lepsze niż posiadanie kodu z NSComparisonResults - niezrozumiałego dla dat - bezpośrednio w nim. –

+0

całkiem fajne !!! – BlaShadow

+0

Apple powinien rozważyć wdrożenie tego. Znacznie łatwiejsze niż tworzenie instrukcji przełączania dla wcześniejszych lub równych i późniejszych niż lub równych. – geekinit

15

tą metodą także możesz compa Re dwiema datami

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

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

} 
+2

Interesujące stałe do porównania z może być: 'NSOrderedAscending',' NSOrderedSame' i 'NSOrderedDescending', ale OP prawdopodobnie chce' NSOrderedSame' dla swojego szczególnego problemu. – Kris

1

Oto wariant Swift na odpowiedź Pascala:

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) 
    } 
} 

który może być używany jako:

self.expireDate.isEarlierThanOrEqualTo(NSDate()) 
1

Oto funkcja z odpowiedzią Naveed Rafi jest konwertowany do Swift czy ktoś inny go szuka:

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) 
} 
0
Get Today's 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]; 

Następnie użyj NSComparisonResult, aby porównać datę.