2011-12-16 101 views

回答

4

約ISO8601日期和時間格式的偉大的事情是,你可以簡單地按字母順序比較字符串。因此,您可以將當前時間寫入ISO8601格式的NSString,然後在兩個字符串上使用NSString的compare方法。

但是,通常比較NSDate對象更好。我用兩個輔助功能使用strftimestrptime的ISO日期字符串,是一個NSDate之間轉換 - 這些功能只是做yyyy-mm-dd的一部分,但你應該能夠輕鬆地擴展他們足夠:

NSString* ISOStringWithDate(NSDate* date) 
{ 
    char buf[11]; // Enough space for "yyyy-mm-dd\000" 
    time_t clock = [date timeIntervalSince1970]; 
    struct tm time; 
    gmtime_r(&clock, &time); 
    strftime_l(buf, sizeof(buf), "%Y-%m-%d", &time, NULL); 
    return [NSString stringWithUTF8String:buf]; 
} 

NSDate* dateWithISOString(NSString* dateString) 
{ 
    struct tm time; 
    memset(&time, 0, sizeof(time)); 
    if (!strptime_l([dateString UTF8String], "%Y-%m-%d", &time, NULL)) 
    { 
     return nil; 
    } 
    time_t clock = timegm(&time); 
    return [NSDate dateWithTimeIntervalSince1970:clock]; 
} 
4

使用Peter Hosey的ISO8601DateFormatter類將其解析爲NSDate對象,然後將其與[NSDate date]進行比較。

一個例子:

NSString *iso8601String = ...; 
ISO8601DateFormatter *formatter = [[ISO8601DateFormatter alloc] init]; 
NSDate *isoDate = [formatter dateFromString:iso8601String]; 
[formatter release]; //if you're not using ARC 

BOOL isBeforeCurrent = [[NSDate date] compare:isoDate] == NSOrderedAscending; 
+0

是有沒有更簡單如何做到這一點?如果可能的話,我不想使用庫 – Suchi 2011-12-16 18:43:40

+0

@Suchi恐怕現在我想不出一個更簡單的方法。 – 2011-12-16 18:45:31