我想查看“2011-03-29T15:57:02.680-04:00”之类的时间是否在当前时间之前。我该怎么做呢?
答案 0 :(得分: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;
答案 1 :(得分:4)
ISO8601日期和时间格式的优点在于您可以简单地按字母顺序比较字符串。因此,您可以将当前时间写入ISO8601格式的NSString,然后在两个字符串上使用NSString的compare
方法。
但是,比较NSDate
个对象通常会更好。我使用两个辅助函数来使用strftime
和strptime
在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];
}