iOS - 如何比较两个 ISO 8601 格式的时间?
我想检查“2011-03-29T15:57:02.680-04:00”之类的时间是否在当前时间之前。我该怎么做呢?
I want to check if a time such as "2011-03-29T15:57:02.680-04:00" is before the current time. How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ISO8601 日期和时间格式的优点在于您可以简单地按字母顺序比较字符串。因此,您可以将当前时间写入 ISO8601 格式的 NSString,然后对两个字符串使用 NSString 的
compare
方法。但是,通常最好比较
NSDate
对象。我使用两个辅助函数来使用strftime
和strptime
在 ISO 日期字符串和 NSDate 之间进行转换 - 这些函数只执行yyyy-mm-dd
code> 部分,但您应该能够足够轻松地扩展它们:The great thing about ISO8601 date and time formats is that you can simply compare the strings alphabetically. So you can write the current time to an NSString in ISO8601 format and then use NSString's
compare
method on the two strings.However, it's often better to compare
NSDate
objects. I use two helper functions to convert between an ISO date string and an NSDate usingstrftime
andstrptime
-- these functions just do theyyyy-mm-dd
part, but you should be able to extend them easily enough:使用 Peter Hosey 的
ISO8601DateFormatter
类将其解析为NSDate
对象,然后将其与[NSDate date]
进行比较。一个例子:
Use Peter Hosey's
ISO8601DateFormatter
class to parse it into anNSDate
object and then compare that with[NSDate date]
.An example: