我想检查诸如“2011-03-29T15:57:02.680-04:00”之类的时间是否早于当前时间。我该怎么做呢?
最佳答案
ISO8601 日期和时间格式的优点在于您可以简单地按字母顺序比较字符串。因此,您可以将当前时间写入 ISO8601 格式的 NSString,然后在两个字符串上使用 NSString 的 compare
方法。
但是,比较 NSDate
对象通常更好。我使用两个辅助函数在 ISO 日期字符串和使用 strftime
和 strptime
的 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];
}
关于objective-c - iOS - 如何比较两个 ISO 8601 格式的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8538597/