在iOS中添加一天到当前日期

lak*_*esh 8 date objective-c ios

我看到这篇文章:iOS并找到了明天.

提供的代码是:

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];
Run Code Online (Sandbox Code Playgroud)

问题:我需要在当前日期添加一天,例如,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];
Run Code Online (Sandbox Code Playgroud)

但是当我试图在2013年6月21日到2013年5月21日之间找到区别时 - >仍然会让我回归0个月而不是1个月.

需要一些帮助.

Anu*_*das 15

形成一个日期组件,其中包含您要添加到原始日期的天数.通过将此组件添加到原始日期,从当前日历形成日期.

NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.day = 1;
NSDate *newDate = [[NSCalendar currentCalendar]dateByAddingComponents:dateComponents 
                                                               toDate: selectedDate 
                                                              options:0];
Run Code Online (Sandbox Code Playgroud)


Nik*_*rev 8

这是我使用的方法:

+ (NSDate *)addDays:(NSInteger)days toDate:(NSDate *)originalDate {
    NSDateComponents *components= [[NSDateComponents alloc] init];
    [components setDay:days];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:components toDate:originalDate options:0];
}
Run Code Online (Sandbox Code Playgroud)

有了它,您可以根据需要添加任意天数.它也适用于负数,因此您可以减去天数.