I have 2 field to show the date and time,in one field date is showing correctly by using NSDateFormatter and in another field want to show a time in UIPicker programmatically and put it into the label. Help me in this
Use UIDatePicker
with Time
mode
self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.frame = CGRectMake(0, 0, self.view.frame.size.width, 180.0f); // set frame as your need
self.datePicker.datePickerMode = UIDatePickerModeTime;
[self.view addSubview: self.datePicker];
And set selected time in UILabel
such like
UILabel * label1 = [[UILabel alloc] initWithFrame:CGRectMake(40, 70, 300, 50)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString *currentTime = [dateFormatter stringFromDate:self.datePicker.date];
label1.text = currentTime;
[self.view addSubview:label1];
Edited:
Add following code to datePicker
[datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
And call this method
- (void)dateChanged:(id)sender
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString *currentTime = [dateFormatter stringFromDate:self.datePicker.date];
NSLog(@"%@", currentTime);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With