2

I have a textfield where the user can enter their date of birth, now i wants to make sure whether the input is of date format before saving into database. I gone through the SO , but still i didn't get the answer. Can anyone tell me how to validate(is it date) the input.

The date format would be MM/DD/YYYY

Note:I don't want the user to select date through date picker.

4

4 回答 4

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
} 
于 2013-07-24T07:39:21.623 回答
1

首先,使用UIDatePicker它是专门为此设计的,它是在 iOS 平台上选择日期的一种自然方式。无论如何,如果您想检查字符串 fromUITextField是否是日期,请对其进行格式化(使用格式化程序)并根据格式化程序获取日期

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”

于 2013-07-24T07:39:57.057 回答
1

在我的 iPhone 应用程序中将字符串转换为日期

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

于 2013-07-24T07:36:44.013 回答
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.
}
于 2013-07-24T08:49:22.610 回答