两个NSDate对象之间的差异 - 结果也是一个NSDate [英] Difference between two NSDate objects -- Result also a NSDate

查看:99
本文介绍了两个NSDate对象之间的差异 - 结果也是一个NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个NSDate对象,我想要两者之间的差异,结果应该是一个NSDate对象。任何想法如何实现这一点?

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?

在这里,我试图解决一个独特的问题,我必须找出经过的时间,然后本地化经过的时间。我可以本地化它,如果我有在NSDate对象的时间。所以想到创建一个NSDate对象,它的时间组件与两个日期之间的时间间隔相同,这样我可以使用NSDateFormatter进行本地化。

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.

推荐答案

NSDate 表示时间上的实例,因此将时间间隔表示为 NSDate 。你想要的是 NSDateComponents

NSDate represents an instance in time, so it doesn't make sense to represent an interval of time as an NSDate. What you want is NSDateComponents:

NSDate *dateA;
NSDate *dateB;

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
                                           fromDate:dateA
                                             toDate:dateB
                                            options:0];

NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);

这篇关于两个NSDate对象之间的差异 - 结果也是一个NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆