两个 NSDate 对象之间的差异 -- 结果也是一个 NSDate
我有两个 NSDate 对象,我想要两者之间的差异,结果应该再次是一个 NSDate 对象。知道如何实现这一目标吗?
在这里,我试图解决一个独特的问题,我必须找出经过的时间,然后定位经过的时间。如果我有 NSDate 对象中的经过时间,我可以对其进行本地化。因此想到创建一个 NSDate 对象,其时间分量与两个日期之间的时间间隔相同,以便我可以使用 NSDateFormatter 来本地化它。
I have two NSDate objects and I want the difference between the two and the result should again be a NSDate object. Any idea how to achieve this?
Here, I am trying to address a unique problem where I have to find out the elapsed time and then localize the elapsed time. I can localize it if I have the elapsed time in NSDate object. So thought of creating a NSDate object which has its time component same as time interval between the two dates so that I could use NSDateFormatter to localize it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
NSDate
表示时间中的一个实例,因此将时间间隔表示为NSDate
是没有意义的。你想要的是NSDateComponents
:NSDate
represents an instance in time, so it doesn't make sense to represent an interval of time as anNSDate
. What you want isNSDateComponents
:如果从 2002 年 5 月 5 日减去 2001 年 12 月 12 日,日期是多少?两个日期之间的时间距离不能是日期,它始终是某种间隔。您可以使用 timeIntervalSinceDate: 计算间隔。
要本地化,您可以尝试以下步骤:
您可以使用 NSCalendar 与 dateFromComponents:传入 NSDateComponent。
将 timeInterval 分解为 NSDateComponents 看看如何在 iPhone 上将 NSTimeInterval 分解为年、月、日、小时、分钟和秒?。
最后使用 NSDateFormatter 和 initWithDateFormat:allowNaturalLanguage: 获取本地化字符串。 日期格式字符串语法 显示不同的占位符。
If you subtract 12/12/2001 from 05/05/2002 what will be the date? The chronological distance between two dates can't be a date, it's alway some kind of interval. You can use timeIntervalSinceDate: to calculate the interval.
To localize you can try the following steps:
You can use the NSCalendar with dateFromComponents: passing in a NSDateComponents.
To break down a timeInterval into NSDateComponents look at How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?.
Finally use the NSDateFormatter and initWithDateFormat:allowNaturalLanguage: to get your localized string. The Date Format String Syntax shows the different placeholders.
从
NSDate
类参考中,您有实例方法来执行这些操作 -isEqualToDate:
timeIntervalSinceDate:
From
NSDate
class reference, you have instance methods to do these -isEqualToDate:
timeIntervalSinceDate:
您可以使用
NSDate
的timeIntervalSinceDate:
计算两个日期之间的时间间隔,但将时间间隔表示为日期没有任何意义。You can calculate the time interval between two dates using
NSDate
'stimeIntervalSinceDate:
, but it doesn't make any sense for you to represent a time interval as a date.在 NSDate 中使用 -compare: 有一个简单的方法:
There is a easy way by using -compare: in NSDate: