检查NSString的具体日期格式

Hen*_*ale 6 cocoa-touch nsdate nsstring ios

我有一个NSString,我需要检查它是否采用这种特定格式MM/DD/YY.然后我需要将其转换为NSDate.任何有关这方面的帮助将非常感激.旁注 - 我已经搜索过,人们建议使用RegEx,我从来没有使用过这个,一般都不清楚.谁能指出我一个很好的资源/解释.

Dyl*_*ann 7

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)
Run Code Online (Sandbox Code Playgroud)

因此,如果NSDate为零,您将知道何时格式不正确.如果您需要更多信息,请参阅以下文档的链接:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369- SW1


Wai*_*ain 6

使用NSDateFormatter两个任务.如果您可以将字符串转换为日期,那么它的格式正确(并且您已经有了结果).