获得两个NSDate之间的精确时间差异? [英] Get an Accurate Time Difference Between two NSDate?

查看:144
本文介绍了获得两个NSDate之间的精确时间差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法找出两个 NSDate 之间的准确差异?

Is there any way to find out an accurate difference between two NSDate?

他们不够准确。我需要考虑夏令时,不同月份有不同的天数等。

I have found solutions but they aren't accurate enough. I need to take into account daylight saving, the fact that different months have a different number of days, etc.

一个简单的计算,如/ 60/60/24等

A simple calculation such as /60/60/24 etc. to work out minutes, hours and days doesn't take them into account.

假设我需要计算出现在时间之间的差异( [NSDate date] )和12月25日下午10:22(用户使用日期选择器 [datePicker date] 选择的日期)例如,我该如何做?

知道确切的时间差异不是关键,只要我有天,月和年的准确差异,它会做。

Lets say I need to work out the difference between the time right now ([NSDate date]) and December 25th 10:22PM (date chosen by user using date picker [datePicker date]) just as an example, how would I do this?
Knowing the exact time difference isn't the key, so long as I have an accurate difference of days, months and years, it will do.

推荐答案

从Apple的 Date&时间编程指南

清单12 获得两个日期之间的区别

Listing 12 Getting the difference between two dates

NSDate *startDate = ...;
NSDate *endDate = ...;

NSCalendar *gregorian = [[NSCalendar alloc]
                 initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                          fromDate:startDate
                                          toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];

这篇关于获得两个NSDate之间的精确时间差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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