Reputation: 585
My datepicker is sending a date to a label. However, I am trying to format my date in the label to MM/dd/yyyy. Somehow, this is not working, although I am using the following code:
UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height+44, 768, 216)];
datePicker.tag = 10;
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker setBackgroundColor:[UIColor whiteColor]];
[datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
And then I am unsuccessfully trying to change the label to the date selected:
- (void)changeDate:(UIDatePicker *)sender {
NSLog(@"New Date: %@", sender.date);
NSDate *date_JF = sender.date;
NSDateFormatter *dateFormatJF = [[NSDateFormatter alloc]init];
[dateFormatJF setLocale:([[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"])];
[dateFormatJF setDateStyle:NSDateFormatterMediumStyle];
[dateFormatJF setDateFormat:@"MM/dd/yyyy"];
FeeDate.text = [NSString stringWithFormat: @"%@", date_JF];
}
Can anyone help me format my label to MM/dd/yyyy?
Upvotes: 0
Views: 48
Reputation: 4336
The correct way to use NSDateFormatter
is by getting the formatted date with the stringFromDate:
method. Therefore you need to change the last line of your code to:
FeeDate.text = [dateFormatJF stringFromDate:date_JF];
Upvotes: 1