3

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

你会帮我这样做吗?

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

4

3 回答 3

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 是一个整数,表示您要从当天添加/减去的天数。

于 2012-08-21T08:10:44.270 回答
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;
}
于 2014-07-03T11:45:12.380 回答
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;
}
于 2014-02-27T22:38:10.237 回答