问题描述
如何计算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);
编辑:
记住, 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.
这篇关于如何计算两个日期之间的差额?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!