在一天之后和之前一天的选择目标-c之前添加当前日期

时间:2012-08-21 07:31:08

标签: objective-c ios datepicker nsdate

我有一个日期选择器,我想只有一行有3个选项:当天,前一天和前一天。

你能帮我这么做吗?

我的问题是,如何在一天后和前一天添加“当天”?

3 个答案:

答案 0 :(得分:5)

NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:days];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *end = [gregorian dateByAddingComponents:components toDate:[NSDate date] options:0];

其中days是一个整数,表示您想要从当天加/减的天数。

答案 1 :(得分:1)

这就是我的做法 -

 -(void)getDate{
    NSString *str_CurDate  =[self getCurrentDate];
    NSString *str_NextDay  =[self getFormattedDate:[self dateByAddingDays:1]];
    NSString *str_PrevDay  =[self getFormattedDate:[self dateByAddingDays:-1]];

}

现在实现这些方法

-(NSString*)getCurrentDate{

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"d/M/yyyy"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
return dateString;

}


- (NSDate *) dateByAddingDays:(int)days {

NSDate *retVal;
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:days];

NSCalendar *gregorian = [[NSCalendar alloc]    initWithCalendarIdentifier:NSGregorianCalendar];
retVal= [gregorian dateByAddingComponents:components toDate:[NSDate date] options:0];

return retVal;

}


-(NSString*)getFormattedDate:(NSDate*)myDate{

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"d/M/yyyy"];
NSString *dateString = [dateFormatter stringFromDate:myDate];

return dateString;
}

答案 2 :(得分:0)

封装在NSDate

上的类别中
- (NSDate *) dateByAddingDays:(int)days {
    NSDate *retVal;
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:days];

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    retVal = [gregorian dateByAddingComponents:components toDate:self options:0];
    return retVal;
}