Search code examples
iosobjective-cuilabelnsdateupdates

Change date in UILabel when click next and previous UIButton


Set a date in UILabel. The click on "next" and "previous" buttons should change date inside this label.

I'm trying this code but next button click and show date next day date for e.g 01/05/2015 and previous button click and set date 29/05/2015 and next button click not display 02/05/2015

- (IBAction)changeToNextDay:(id)sender
{
    NSDateComponents* deltaComps = [[NSDateComponents alloc] init];
    [deltaComps setDay:+1];
    NSDate* tomorrow = [[NSCalendar currentCalendar]  dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];

    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"dd-MM-yyyy"];

    NSString *stringFromDate = [myDateFormatter  stringFromDate:tomorrow];
    dateLabel.text = stringFromDate;
}

- (IBAction)changeToPreviousDay:(id)sender
{
    NSDate *datePlusOneDay = [[NSDate date] dateByAddingTimeInterval:-(60 * 60 * 24)];
    NSLog(@"datePlusOneDay=%@",datePlusOneDay);

    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"dd-MM-yyyy"];

    NSString *stringFromDate = [myDateFormatter stringFromDate:datePlusOneDay];
    dateLabel.text = stringFromDate;
}

Solution

  • - (void)viewDidLoad {
        [super viewDidLoad];
        [self Update_Date_By:0];
    }
    
    - (IBAction)changeToNextDay:(id)sender {
        [self Update_Date_By:1];
    }
    
    - (IBAction)changeToPreviousDay:(id)sender {
        [self Update_Date_By:-1];
    }
    
    -(void)Update_Date_By:(NSInteger)value {
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"dd/MM/yyyy"];
        NSDate *date = [dateFormat dateFromString:dateLabel.text];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *dateComponents = [NSDateComponents new];
        dateComponents.day = value;
        if (value == 0) {
            date = [NSDate date];
        }
        NSDate *newDate = [calendar dateByAddingComponents:dateComponents toDate:date options:0];
        [dateFormat setDateFormat:@"dd/MM/yyyy"];
        NSString *finalDate_String = [dateFormat stringFromDate:newDate];
        dateLabel.text = finalDate_String;
    }