在iOS中添加当前日期的一天 [英] Adding a day to current date in iOS

查看:213
本文介绍了在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];

问题:我需要在当前日期添加一天,例如21世纪2013年6月和2013年5月21日是1个月而不是0个月。

Problem: I need to add a day to my current date so that for example, the difference between 21st Jun 2013 and 21st May 2013 is 1 month instead of 0 month.

我使用的代码:

    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个月。

But when I tried to get the difference between 21st Jun 2013 and 21st May 2013 -> still returns me 0 month instead of 1 month.

需要一些帮助。

推荐答案

表示您要添加到原始日期的天数的日期组件。从当前日历表格的日期通过添加此组件到您的原始日期。

Form a date component with number of days you want to add to your original date. From the current calendar form the date by adding the this component to your original date.

NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.day = 1;
NSDate *newDate = [[NSCalendar currentCalendar]dateByAddingComponents:dateComponents 
                                                               toDate: selectedDate 
                                                              options:0];

这篇关于在iOS中添加当前日期的一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆