【发布时间】:2013-06-21 08:29:35
【问题描述】:
我看到了这个帖子:iOS and finding Tomorrow。
提供的代码是:
units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comps = [[NSCalendar currentCalendar] components:units fromDate:[NSDate date]];
// Add one day
comps.day = comps.day+1; // no worries: even if it is the end of the month it will wrap to the next month, see doc
// Recompose a new date, without any time information (so this will be at midnight)
NSDate* tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];
问题:我需要在当前日期上添加一天,例如,2013 年 6 月 21 日和 2013 年 5 月 21 日之间的差异是 1 个月而不是 0 个月。
我正在使用的代码:
NSDate *selectedDate = [picker2 date];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [currCalendar components:unitFlags fromDate:selectedDate toDate:[NSDate date] options:0];
DLog(@"%i",conversionInfo.month);
DLog(@"%i",conversionInfo.day);
conversionInfo.day +=1;
DLog(@"%i",conversionInfo.day);
DLog(@"%i",conversionInfo.month);
int months = [conversionInfo month];
但是当我试图获得 2013 年 6 月 21 日和 2013 年 5 月 21 日之间的差异时 -> 仍然返回 0 个月而不是 1 个月。
需要一些帮助。
【问题讨论】:
-
如果您只想在今天添加一天,请执行以下操作:
NSDate *tomorrow = [NSDate dateWithTimeInterval:(24*60*60) sinceDate:[NSDate date]];这会将给定日期增加 24*60*60 秒并返回一个新日期。 -
感谢您的快速回复。工作...添加为答案..将其标记为正确..
-
我不明白你问题的最后一句话。为什么 2013 年 6 月 21 日和 2013 年 6 月 20 日的差是 1 个月?
-
对最后一部分道歉.. 输入错误...
-
@lakesh:好的。但是 2013 年 6 月 21 日和 2013 年 5 月 21 日之间的差异 给 一个月(我测试过)。问题可能是两个日期的时间不同。例如,“2013 年 6 月 21 日 00:00”和“2013 年 5 月 21 日 00:30”之间的差异给出了 30 天、23 小时、30 分钟和 0 个月。因此,也许您必须先将日期标准化为午夜。
标签: ios objective-c date