UIDatePicker The selected value is incorrect if the UIDatePicker has not been scrolled

enter image description here

I am creating an iPhone application in which I use UIDatePickerand display the selected time on an action sheet. In the action table, the time is displayed at intervals of 10 minutes.

textfield value is set correctly when I browse Datepicker

If I do not scroll through the action sheet, click directly on the selection button, then the text field sets the current time ( 11:56), but I select ( ) in the list of actions . ( ) shows the wrong value. 11:50textfield

How to set the value textfield( 11:50). Give me some solution.

+5
source share
4 answers

UIControlEventValueChanged . ViewDidLoad :

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

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

, , .


UPDATE

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

textField :

  self.dateTextField.text = strdate;
+1

....

NSDate *date = datePicker.date;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy"];    
NSString *dateString = [formatter stringFromDate:date];
yourTxtField.text = dateString;
+1

, - TextField, UIDatePicker . TextField, TextViewDidBeginEditing. - :

if (_currentTextField == _myTextFieldThatUsesADatePicker) {
    self.myDateProperty = _myDatePicker.date;
}
0

I don’t know how right it is wrong, but his work is for me

-(void)selectedTime{
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
//    [outputFormatter setDateFormat:@"h:mm a"];
    [outputFormatter setDateFormat:@"HH:mm:ss"];
    selectedTime = [outputFormatter stringFromDate:datePicker.date];
    NSArray *temp=[selectedTime componentsSeparatedByString:@":"];
    NSLog(@"%@",temp);
    NSInteger mins=[[temp objectAtIndex:1]integerValue];
    //check your interval here
    if (mins<=29) {
        selectedTime=[NSString stringWithFormat:@"%@:%@:%@",[temp objectAtIndex:0],@"00",@"00"];
    }else if (mins>=31 && mins<=59){
        selectedTime=[NSString stringWithFormat:@"%@:%@:%@",[temp objectAtIndex:0],@"30",@"00"];
    }else{
//        selectedTime = [outputFormatter stringFromDate:datePicker.date];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(SelectedValue:)]) {
        [self.delegate SelectedValue:selectedTime];
    }
    [self.popupController dismiss];
}

My interval is 30 minutes

0
source

All Articles