开发者

iPhone SDK: Testing for valid string date

开发者 https://www.devze.com 2023-01-18 23:45 出处:网络
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.

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

精彩评论

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