user1850984
user1850984

Reputation: 41

Showing a particular date in UIDatePicker in UIDatePickerModeDate on the iPhone

I have an NSString object that contains the string 2013-02-28. By default, the UIDatepicker shows the current date, but I want to show whatever date I had in the NSString object.

I am converting the NSString object into NSDate and I don't know how to set that date on UIDatePicker in UIDatePickerModeDate. How could I do this? I have tried the setDate: method, but it's not working.

Upvotes: 1

Views: 2416

Answers (2)

Rinku
Rinku

Reputation: 920

-(IBAction)btnDateClicked:(id)sender{

    theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, self.view.frame.size.width, 0.0)];
    theDatePicker.datePickerMode = UIDatePickerModeDate;
    theDatePicker.minimumDate=[NSDate date];

    // ************To keep the selected date**********

    NSString *dateString = [NSString stringWithFormat:@"%@",btnDate.titleLabel.text ];
    NSTimeZone *timezone = [NSTimeZone systemTimeZone];

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

    NSDate *date = [dateFormatter dateFromString:dateString];
    theDatePicker.date = date;
}

Upvotes: 1

Brad The App Guy
Brad The App Guy

Reputation: 16275

This should work for you. You likely need to turn your NSString into a NSDate before sending it to the NSDatePicker. Keep in mind that you may need to set the Timezone of the NSDateFormater to avoid edge cases.

  //Given self.datepicker is your UIDatePicker 

  NSString *dateString = @"2013-03-28";
  NSTimeZone *timezone = [NSTimeZone systemTimeZone];

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

  NSDate *date = [dateFormatterGMTAware dateFromString:dateString];
  self.datePicker.date = date;

Upvotes: 4

Related Questions