Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIDatePicker Selected value is wrong in case UIDatePicker was not scrolled

enter image description here

I am making an iPhone app in which I am using UIDatePicker and displaying the selected the time in a actionsheet. In actionsheet the time is displaying with 10 mints interval.

textfield value is set correctly when I do scroll the Datepicker

If I don't scroll the action sheet then direct click on select button then text field set the current time (11:56) but I select in action sheet (11:50) time. (textfield) shows the incorrect value.

How can I set the textfield's value (11:50). Give me some solution.

like image 298
Rinju Jain Avatar asked Aug 24 '12 06:08

Rinju Jain


2 Answers

Just set the dateSelected from your date picker after select button press....

NSDate *date = datePicker.date;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy"];    
NSString *dateString = [formatter stringFromDate:date];
yourTxtField.text = dateString;
like image 199
Rajneesh071 Avatar answered Oct 30 '22 08:10

Rajneesh071


EDIT Make your class to handle UIControlEventValueChanged event in your picker. Add this line ViewDidLoad method or when your actionsheet shown:

  [picker addTarget:self action:@selector(dateChanged:) 
          forControlEvents:UIControlEventValueChanged];

Now selector would be called when date is changed

UPDATE

- (void) dateChanged:(id)sender{
    // handle date changes and set in textField
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSString *strdate = [dateFormatter stringFromDate:self.datePicker.date]; //provide your selected date here
    self.dateTexField.text = strdate;
}

If above method is not called means date is not changed so always set default date in your textField.


Convert date to string object

UPDATE

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 NSString *strdate = [dateFormatter stringFromDate:self.datePicker.date]; //provide your selected date here

Now set value to textField like this:

  self.dateTextField.text = strdate;
like image 20
Paresh Navadiya Avatar answered Oct 30 '22 08:10

Paresh Navadiya