问题描述
如何计算2010年1月1日至(例如)2010年2月3日之间的天数。
How can I calculate the days between 1 Jan 2010 and (for example) 3 Feb 2010?
推荐答案
NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(@"There are %d days in between the two dates.", numberOfDays);
编辑:
c $ c> NSDate 对象表示精确的时刻,它们没有任何相关的时区信息。当您使用例如字符串将字符串转换为日期。 NSDateFormatter
,则 NSDateFormatter
将从配置的时区转换时间。因此,两个 NSDate
对象之间的秒数总是与时区无关。
Remember, NSDate
objects represent exact moments of time, they do not have any associated time-zone information. When you convert a string to a date using e.g. an NSDateFormatter
, the NSDateFormatter
converts the time from the configured timezone. Therefore, the number of seconds between two NSDate
objects will always be time-zone-agnostic.
此外,指定Cocoa的时间实现不考虑闰秒,因此,如果您需要这样的准确性,您需要滚动自己的实现。
Furthermore, this documentation specifies that Cocoa's implementation of time does not account for leap seconds, so if you require such accuracy, you will need to roll your own implementation.
这篇关于如何计算两个日期之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!