objective-c - iOS - 如何比较两个 ISO 8601 格式的时间?

标签 objective-c ios nsdate iso8601

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

最佳答案

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

但是,比较 NSDate 对象通常更好。我使用两个辅助函数在 ISO 日期字符串和使用 strftimestrptime 的 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/

相关文章:

objective-c - IKImageView 导致 App 崩溃

ios - UITableViewCell 在 iOS 7 中卡住白色

ios - 如何向 UITableViewCell 添加触摸识别器?

iOS - 自定义 UISearchBar 的取消按钮

ios - 如何设置: 2015-06-17 05:25:21 +0000 as a let NSDate constant

ios - dateFromString在ios 6中工作,但不在ios 5中工作

objective-c - 如何防止 UIImagePickerController 改变方向?

iPhone使用iTunes传输文件,但不允许用户查看所有文档目录?

ios - 为什么日期格式化程序崩溃?

objective-c - 没有简单的划分