输入字符串的验证是否为日期?

时间:2013-07-24 07:25:38

标签: ios nsdate

我有一个文本字段,用户可以输入他们的出生日期,现在我想确保在保存到数据库之前输入是否为日期格式。我经历了SO,但我仍然没有得到答案。任何人都可以告诉我如何验证(是日期)输入。

日期格式为MM / DD / YYYY

注意:我不希望用户通过日期选择器选择日期。

4 个答案:

答案 0 :(得分:4)

试试这个

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
} 

答案 1 :(得分:1)

Convert string to date in my iPhone app

然后检查它是否为零。也许还要检查它是否在你的应用程序的合理范围内

答案 2 :(得分:1)

首先,使用UIDatePicker,因为它是专门设计的,这是在iOS平台上选择日期的自然方式。 无论如何,如果你想检查来自UITextField的字符串是否是日期,格式化(使用格式化程序),并依赖格式化程序获取日期

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

如果NSDate不是nil,那就没关系,否则出现问题:用户输入的不是用户输入格式错误的日期或日期。

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

答案 3 :(得分:0)

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.
}