ios 如何计算iOS中两个日期之间的时差(以分钟为单位)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10373911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate time difference in minutes between two dates in iOS
提问by Sagar Mohanty
Possible Duplicate:
How to calculate time in hours between two dates in iOS
I am beginner to Objective-C, so I need your help in syntax making.
我是 Objective-C 的初学者,所以我需要你在语法制作方面的帮助。
My problem goes like this:
我的问题是这样的:
I have 2 Strings, and I want to convert that into NSDate
and then calculate the time difference between the dates in minutes.
我有 2 个字符串,我想将其转换为NSDate
然后以分钟为单位计算日期之间的时差。
How can I do this?
我怎样才能做到这一点?
回答by Ole Begemann
- Use
NSDateFormatter
to convert the date strings intoNSDate
objects. - Call
-[NSDate timeIntervalSinceDate:]
to get the difference between the two dates in seconds. - Divide by 60 to get the difference in minutes.
- 使用
NSDateFormatter
的日期字符串转换成NSDate
对象。 - 调用
-[NSDate timeIntervalSinceDate:]
以秒为单位获取两个日期之间的差异。 - 除以 60 可得到以分钟为单位的差异。
Alternatively, you can use NSCalendar
and NSDateComponents
to calculate the difference in minutes for different calendars by using the components:fromDate:toDate:options:
method.
或者,您可以使用NSCalendar
和NSDateComponents
计算不同日历的分钟差异components:fromDate:toDate:options:
。