从 UITextField 输入验证 NSDate
我有一个问题。我有 3 个文本字段,分别代表日、月、年,用于从用户那里获取日期输入,我不想使用日期选择器。相反,我以 dd/mm/yy 格式从所有三个输入创建一个字符串,并使用像这样的日期格式化程序来评估有效性。
NSDate *convertedDOB = [dobFormatter dateFromString:dateOfBirth];
if (convertedDOB == nil){
NSLog(@"DATE EPIC FAIL");
}
else{
NSLog(@"DATE OK");
}
[dobFormatter release];
如果我输入像 10/40/88 这样的愚蠢内容,它会返回错误,但是 40/12/88 或 30/02/88 类型的日期不会被检测到。我做错了什么吗?谢谢。
I have a problem. I have 3 text field for day, month, year to get date input from the user I do not want to use a date picker. Instead I create a string from all three inputs in the format dd/mm/yy and use a date formatter like so to assess the validity.
NSDate *convertedDOB = [dobFormatter dateFromString:dateOfBirth];
if (convertedDOB == nil){
NSLog(@"DATE EPIC FAIL");
}
else{
NSLog(@"DATE OK");
}
[dobFormatter release];
If I enter something stupid like 10/40/88 it returns an error, however date of the type 40/12/88 or 30/02/88 go undetected. Is there anything I'm doing wrong? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能应该使用 NSDatePicker 以便可以防止此类错误。
http://developer.apple .com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSDatePicker_Class/Reference/Reference.html
另外,您可能会得到
nil
,因为输入的日期格式与 NSDateFormatter 的日期格式不同。You should probably use NSDatePicker so that errors like this can be prevented.
http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSDatePicker_Class/Reference/Reference.html
Also, you may be getting
nil
as the date format entered is different to the date format of the NSDateFormatter.