我有一个日期选择器,我希望只有一行有 3 个选项:当前日期、后一天和前一天。
你会帮我这样做吗?
我的问题是,如何在后一天和前一天添加“当前日期”?
我有一个日期选择器,我希望只有一行有 3 个选项:当前日期、后一天和前一天。
你会帮我这样做吗?
我的问题是,如何在后一天和前一天添加“当前日期”?
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 是一个整数,表示您要从当天添加/减去的天数。
我就是这样做的——
-(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;
}
封装在一个类别中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;
}