我正在尝试将 NSString 转换为秒,但我做错了什么。这是我的代码:
_myTextField 中的文本来自 uidatepicker,格式为 HH:mm。
NSString *teste = [[NSString alloc]init];
teste = [_myTextField text];
NSDateFormatter *formatarteste = [[NSDateFormatter alloc]init];
[formatarteste setDateFormat:@"s"];
NSDate *dateFromString = [[NSDate alloc]init];
dateFromString = [formatarteste dateFromString:teste];
NSLog(@"%@", dateFromString);
我总是在 nslog 上得到 i null 结果。在使用 NSLog 之前,我尝试将 dateFromString 转换回字符串,但仍然收到空消息。
按照这里的要求,我使用的更多代码是:
我有一个调用 uidatepicker 的文本字段,它在超级 viewdidload 上加载:
[_myTextField setText:@"03:00"];
UIDatePicker *datepicker = [[UIDatePicker alloc]init];
//[datepicker setDate:[NSDate date]];
[datepicker setDatePickerMode:UIDatePickerModeTime];
[datepicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
[self.myTextField setInputView:datepicker];
这是 updateTextfield 函数:
UIDatePicker *picker = (UIDatePicker*)self.myTextField.inputView;
NSDateFormatter *formatar = [[NSDateFormatter alloc]init];
[formatar setDateFormat:@"HH:mm"];
NSString *textoDoField = [formatar stringFromDate:picker.date];
self.myTextField.text = [NSString stringWithFormat:@"%@", textoDoField];