2011-10-12 158 views

回答

42

試試這個:

注意:根據您的需要更改日期格式。

NSDateFormatter* df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"MM/dd/yyyy"]; 
NSDate* enteredDate = [df dateFromString:@"10/04/2011"]; 
NSDate * today = [NSDate date]; 
NSComparisonResult result = [today compare:enteredDate]; 
switch (result) 
{ 
    case NSOrderedAscending: 
     NSLog(@"Future Date"); 
        break; 
    case NSOrderedDescending: 
     NSLog(@"Earlier Date"); 
        break; 
    case NSOrderedSame: 
     NSLog(@"Today/Null Date Passed"); //Not sure why This is case when null/wrong date is passed 
        break; 
} 
+5

每個案例陳述後應該有一箇中斷,以免在其他案件中輸入。 –

+0

請注意,這將永遠不會返回「今天」 - NSDate代表一個特定的時間即時,所以'NSOrderedSame'將(實質上)永遠不會發生 – Tim

7

Apple's documentation on date calculations

NSDate *startDate = ...; 
NSDate *endDate = ...; 

NSCalendar *gregorian = [[NSCalendar alloc] 
       initWithCalendarIdentifier:NSGregorianCalendar]; 

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; 

NSDateComponents *components = [gregorian components:unitFlags 
              fromDate:startDate 
              toDate:endDate options:0]; 
NSInteger months = [components month]; 
NSInteger days = [components day]; 

如果days是+1和-1,那麼您的日期之間是「今天」的候選人。顯然你需要考慮你如何處理小時。推測最簡單的方法是將所有日期設置爲當天00:00時(truncate the date using an approach like this),然後使用這些值進行計算。這樣你今天得到0,昨天得到-1,明天得+1,而其他任何價值都會告訴你未來或過去有多遠。

+0

這會起作用,但爲避免夏時制變化出現錯誤,將小時設置爲中午(12:00:00)會更安全。 – Suz

+0

具有諷刺意味的是,我原來建議將時間設置爲中午,但截斷的例子已將其設置爲午夜,我認爲可以保持一致!但是,如果兩個日期都在同一個時區,那麼這將不會產生任何影響,因爲夏令時會在凌晨2點發生變化,並將時鐘恢復爲凌晨1點,因此在所有情況下,來自同一時區的兩個日期將截斷爲相同的日曆日期,無論夏時制如何。 –

+0

如果您實際上想要考慮時區,最好的方法是在做其他任何事情之前將這兩個日期轉換爲同一時區。 –

1
-(NSString*)timeAgoFor:(NSString*)tipping_date 
{ 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
    NSDate *date = [dateFormatter dateFromString:tipping_date]; 
    NSString *key = @""; 
    NSTimeInterval ti = [date timeIntervalSinceDate:[NSDate date]]; 
    key = (ti > 0) ? @"Left" : @"Ago"; 

    ti = ABS(ti); 
    NSDate * today = [NSDate date]; 
    NSComparisonResult result = [today compare:date]; 

    if (result == NSOrderedSame) { 
     return[NSString stringWithFormat:@"Today"]; 
    } 
    else if (ti < 86400 * 2) { 
     return[NSString stringWithFormat:@"1 Day %@",key]; 
    }else if (ti < 86400 * 7) { 
     int diff = round(ti/60/60/24); 
     return[NSString stringWithFormat:@"%d Days %@", diff,key]; 
    }else { 
     int diff = round(ti/(86400 * 7)); 
     return[NSString stringWithFormat:@"%d Wks %@", diff,key]; 
    } 
} 
+0

我用這個,但不知何故今天從來沒有過,所以我不得不修改它,以便我只比較日期。休息工作正常。最後得到了它與它的時間比較的問題。我必須做相應的調整 – ChArAnJiT

相關問題