0

我想检查诸如“2011-03-29T15:57:02.680-04:00”之类的时间是否早于当前时间。我该怎么做呢?

4

2 回答 2

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;
于 2011-12-16T18:41:04.437 回答
4

ISO8601 日期和时间格式的优点在于您可以简单地按字母顺序比较字符串。因此,您可以将当前时间写入 ISO8601 格式的 NSString,然后compare在这两个字符串上使用 NSString 的方法。

但是,比较NSDate对象通常更好。我使用两个辅助函数在 ISO 日期字符串和 NSDate 之间进行转换,使用strftimestrptime-- 这些函数只是做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];
}
于 2011-12-16T19:50:26.747 回答