ios - 两个日期之间经过的天数总是相差一天

标签 ios objective-c nsdate nscalendar

我正在尝试计算两个日期之间的天数。这是我的做法:

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

unsigned int calendarFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDate *dateToCheck = (self.subscriptionEnd ?: self.trialEnd);
NSLog(@"dateToCheck: %@", dateToCheck);
NSLog(@"current date: %@", [self systemTimeZoneDate]);
NSDateComponents *components = [gregorian components:calendarFlags
                                            fromDate:[self systemTimeZoneDate]
                                              toDate:dateToCheck
                                             options:0];
return [components day] >= 0 ?: 0;

在撰写本文时,NSLog 输出以下内容:

2014-09-05 22:56:20.054 tweepy[9635:60b] dateToCheck: 2014-10-05 08:02:51 PM +0000
2014-09-05 22:56:20.057 tweepy[9635:60b] current date: 2014-09-05 10:56:20 PM +0000

它返回一天的差异,因为 iOS 认为该天采用 YDM 格式。

我应该在某处指示日期格式吗?

以下是如何设置 self.subscriptionEnd 的代码:

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 30;
self.subscriptionEnd = [gregorianCalendar dateByAddingComponents:dateComponents toDate:[self systemTimeZoneDate] options:0];

以下是如何设置 self.TrialEnd 的代码:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 2;
self.trialEnd = [gregorian dateByAddingComponents:dateComponents toDate:[self systemTimeZoneDate] options:0];

最佳答案

日期格式与它没有任何关系。正在发生的事情是 NSDateComponents 为您提供了您所要求的,即年、月和日的总差异。如果您只需要天数,则只需提供 NSDayCalendarUnitdocs说清楚:

Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days.

关于ios - 两个日期之间经过的天数总是相差一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694676/

相关文章:

ios - 可以不在自定义 init 方法中调用 [super init] 吗?

ios - 您可以从一个类发送消息以触发另一个类中的 'self' 吗?

ios - 从 iOS 中的日期中删除时区偏移

ios - 为什么 GCDAsyncSocket 总是在读取超时后断开连接?

objective-c - 使用 Cocoa 上传文件夹

iphone - NSDate 没有返回正确的日期

iphone - 使用 strftime 将 NSDate 转换为字符串

ios - 点击 UICollectionView 时更改单元格颜色

ios - 持续集成与部署 : Bots + Testflight Api on Itunes Connect

c# - Xamarin iOS 在 UIWebView 中加载内容