开发者

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 s开发者_StackOverflow社区ure that the value entered is indeed a date.

Thanks in advance.


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


If (date) { 
// CORRECT
}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜