inputstring的validation是否为Date?

我有一个用户可以input他们的出生date的文本字段,现在我想确保input是保存到数据库之前的date格式。 我经历了这个SO,但是我仍然没有得到答案。 谁能告诉我如何validation(是date)的input。

date格式为MM / DD / YYYY

注意:我不希望用户通过dateselect器selectdate。

尝试这个

NSString *dateFromTextfield = @"07/24/2013"; // Convert string to date object NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"MM/dd/yyyy"];// here set format which you want... NSDate *date = [dateFormat dateFromString:dateFromTextfield]; [dateFormat release]; 

然后检查

 //set int position to 2 and 5 as it contain / for a valid date unichar ch = [dateFromTextfield characterAtIndex:position]; NSLog(@"%c", ch); if (ch == '/') { //valid date } else { //not a valid date } 

在我的iPhone应用中将string转换为date

然后检查是否是零。 也许还要检查,无论你的应用程序是在一个合理的范围内

首先,使用UIDatePicker是因为它专门为此devise的,这是在iOS平台上selectdate的一种自然方式。 无论如何,如果你想检查从UITextFieldstring是一个date,格式(使用格式化程序),并取决于格式化date

 NSString *dateAsString = @"2010-05-24" // string from textfield NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate * dateFromString = [myDateFormatter dateFromString:dateAsString]; 

如果NSDate不为零,那么没关系,否则有些事情是错误的:用户input的不是用户input的格式错误的date或date。

试着为用户提供一个提示,例如:'date应该有格式:yyyy-dd-MM'

 NSString *dateFromTextfield = @"07/24/2013"; //Extra validation, because the user can enter UTC date as completely in textfield, //Here i assumed that you would expect only string lenth of 10 for date //If more than digits then invalid date. if ([dateFromTextfield length]>10) { //Show alert invalid date return; } //If you give the correct date format then only date formatter will convert it to NSDate. Otherwise return nil. //So we can make use of that to find out whether the user has entered date or not. NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"MM/dd/yyyy"]; NSDate *date = [dateFormat dateFromString:dateFromTextfield]; [dateFormat release]; //If date and date object is kind of NSDate class, then it must be a date produced by dateFormat. if (date!=nil && [date isKindOfClass:[NSDate class]]) { //User has entered date // '/' and numbers only entered } else{ //Show alert invalid date //Other than that date format. }