butchcowboy
butchcowboy

Reputation: 565

iPhone SDK: Testing for valid string date

I want to be able to validate a date.

It's valid entry is 4 characters with a mmyy mask.

I want to make sure that the value entered is indeed a date.

Thanks in advance.

Upvotes: 1

Views: 1959

Answers (3)

Michael
Michael

Reputation: 1

This dateFormatter-thing is inconvinient to me since it accepts to many things as valid date. ok, the day after yesus was born is indeed a valid date ;-) and also dateformatter is removing 1 hour from my datestring because it seems to calculate with utc time or so...thats why i like to check for correct dates with regular expressions:

[textfield.text rangeOfString:@"^(0[1-9]|[1-2][0-9]|3[0-1])(0[1-9]|1[0-2])(19|20)[0-9]{2}" options:NSRegularExpressionSearch].location == NSNotFound

this example is for german date format

Upvotes: 0

vodkhang
vodkhang

Reputation: 18741

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mmyy"];
NSDate *date = [dateFormatter dateFromString:YOUR_STRING];


If (date) { 
// CORRECT
}

Upvotes: 4

user23743
user23743

Reputation:

User NSDateFormatter's -setDateFormat: and -dateFromString: methods. If the string is not in the correct format, you will get nil returned from -dateFromString:.

Upvotes: 0

Related Questions