我有一个 NSString,我需要检查它是否采用这种特定格式 MM/DD/YY。然后我需要将其转换为 NSDate。对此的任何帮助将不胜感激。旁注 - 我四处搜索,人们建议使用 RegEx,我从来没有使用过这个,而且一般不清楚。谁能给我指出一个好的资源/解释。
最佳答案
NSString *strDate1 = @"02/09/13";
NSString *strDate2 = @"0123/234/234";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *dateFormat1 = [dateFormatter dateFromString:strDate1];
NSDate *dateFormat2 = [dateFormatter dateFromString:strDate2];
NSLog(@"%@", dateFormat1); // prints 2013-09-02 00:00:00 +0000
NSLog(@"%@", dateFormat2); // prints (null)
因此,如果 NSDate 为 nil,您将知道何时格式不正确。如果您需要更多信息,这里是文档的链接:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
关于ios - 检查 NSString 的特定日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18602602/