3

I have a datepicker and I want to have just one row with 3 options: current day, one day after and one day before .

Would you help me to do that?

My question is, how can I add 'current day' with one day after and one day before ?

LJ Wilson
  • 14,445
  • 5
  • 38
  • 62

3 Answers3

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];

Where days is an integer representing the days you want to add/subtract from the current day.

andreamazz
  • 4,256
  • 1
  • 20
  • 36
  • 3
    This is the [correct](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html#//apple_ref/doc/uid/TP40007836-SW3) way of doing this. – Paul de Lange Aug 21 '12 at 08:47
1

This is how i did-

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

}

Now implement these method

-(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;
}
Nagendra Tripathi
  • 923
  • 12
  • 23
0

Encapsulate in a category on 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;
}
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
  • And check out this category for comparison. Personally, I'd put both of this in +Util: http://stackoverflow.com/a/11934892/8047 – Dan Rosenstark Feb 27 '14 at 22:39