user1498477
user1498477

Reputation:

How can i make a datePicker show the date on a textField?

I have a textField in my view and under it a picker.

I need when the user chooses a date from the datePicker the textField to show the exact value of the date.

How do i get the date from the dateField?

Upvotes: 1

Views: 5690

Answers (4)

Pushkraj Lanjekar
Pushkraj Lanjekar

Reputation: 2294

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = "dd-MMMM-yyyy hh:mm a"

    //To show date in textfield     

    myTextField.text = [df stringFromDate:datePicker.date];

    //To show selected date on datepicker from textfield 

   datePicker.date = df.dateFromString(myTextField.text)

Upvotes: 0

nsgulliver
nsgulliver

Reputation: 12671

You can have a method to update the date changed from the UIDatePicker by setting an action to Value Changed event in the connection inspector, implement the action to set the value to textField something like this

- (IBAction)datePickerValueChanged:(id) sender{

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateStyle = NSDateFormatterMediumStyle;

    self.textfield.text = [NSString stringWithFormat:@"%@",[df stringFromDate:datePicker.date]];

}

OR you could add selector to the UIDatePicker

[datePicker addTarget:self action:@selector(updateMyDate:) forControlEvents:UIControlEventEditingChanged];

Upvotes: 2

vdaubry
vdaubry

Reputation: 11439

Set the value_changed event of your DatePicker to a IBAction :

example :

- (IBAction) dateChanged:(id)sender {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    self.currentTextField.text = [dateFormatter stringFromDate:[self.datePicker date]];
}

Upvotes: 4

Mick F
Mick F

Reputation: 7439

UIDatePicker has a date property. You can access the NSDate via this property.

Then you probably need to use NSDateFormatter to create a NSString from your NSDate, and be able to display it in your UITextField.

In its most straightforward way, your code should look like this:

myTextField.text = [myDateFormatter stringFromDate:myDatePicker.date];

Upvotes: 1

Related Questions