
我的第一个想法是将时间间隔除以一年中的秒数,减去运行的总秒数,在一个月除以秒,减去运行总数,等等。
这看起来很复杂,我读过,每当你做一些看起来很复杂的东西,可能是一个内置的方法。
在那儿?
我将Alex的第二种方法集成到我的代码中。
它在我的接口中的UIDatePicker调用的方法。
NSDate *Now = [NSDate date];NSDate *then = self.datePicker.date;NSTimeInterval howLong = [Now timeIntervalSinceDate:then];NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong];Nsstring *dateStr = [date description];const char *dateStrPtr = [dateStr UTF8String];int year,month,day,hour,minute,sec;sscanf(dateStrPtr,"%d-%d-%d %d:%d:%d",&year,&month,&day,&hour,&minute,&sec);year -= 1970;NSLog(@"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds",year,sec);
当我将日期选择器设置为过去1年和1天的日期时,我得到:
1 years 1 months 1 days 16 hours 0
minutes 20 seconds
这是1个月和16小时。如果我将日期选择器设置为过去的1天,我将关闭相同的金额。
更新:我有一个应用程序,计算您的年龄,以年,给你的生日(从UIDatePicker设置),但它经常关闭。这证明有一个不准确,但我不知道它从哪里来,你能吗?
解决方法 简要描述;简介>只是另一种方法来完成JBRWilkinson的答案,但添加了一些代码。它还可以为Alex Reynolds的评论提供解决方案。
>使用NSCalendar方法:
(NSDateComponents *)组件:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts
>“返回,作为使用指定组件的NSDateComponents对象,两个提供日期之间的差异”。 (从api文档)。
>创建2 NSDate,它的区别是要分解的NSTimeInterval。 (如果你的NSTimeInterval来自比较2 NSDate你不需要做这一步,你甚至不需要NSTimeInterval,只是应用日期NSCalendar方法)。
>从NSDateComponents获取您的报价
示例代码
// The time interval NSTimeInterval theTimeInterval = ...;// Get the system calendarNSCalendar *sysCalendar = [NSCalendar currentCalendar];// Create the NSDatesNSDate *date1 = [[NSDate alloc] init];NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1]; // Get conversion to months,days,hours,minutesNSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0];NSLog(@"Break down: %i min : %i hours : %i days : %i months",[breakdownInfo minute],[breakdownInfo hour],[breakdownInfo day],[breakdownInfo month]);总结
以上是内存溢出为你收集整理的如何在iPhone上将NSTimeInterval分解为年,月,日,小时,分钟和秒?全部内容,希望文章能够帮你解决如何在iPhone上将NSTimeInterval分解为年,月,日,小时,分钟和秒?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)