【发布时间】:2014-09-05 22:11:04
【问题描述】:
我正在计算两个日期之间的天数。这是我的做法:
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];
【问题讨论】:
-
NSDate 对“格式”一无所知。你如何创建存储在你的属性中的 NSDates - 如果你正在解析字符串,那么它肯定会关心格式
-
我在我的问题中添加了新代码。其实我更感兴趣的是找到多少天。
-
如果您使用 NSDateFormatter 将字符串日期解析为 NSDate,并且不指定任何格式,则使用的日期格式将是您所在地区的“默认”格式。此外,日期格式化程序将假定日期值(除非它带有时区指示符)是“本地时间”,并将其映射到生成的 NSDate 对象中的 GMT/UTC 时间。 Net-net 是您必须非常小心注意日期转换操作。 (请记住,NSDate 对象总是应该包含 UTC 时间。)
-
一旦您将日期写入 NSDate 对象,它就没有“格式”,并且它的时区固定为 UTC。当您使用 NSDateFormatter 转换回字符串形式时,您映射到所需的时区和格式。
-
(但请注意NSCalendar确实有时区设置,在提取组件等时需要考虑)
标签: ios objective-c nsdate nscalendar