我想检查一个字符串是否格式为dd.mm.yyyy,就像
if(myString is in format dd.mm.yyyy) {
NSLog(@"Ok");
}
else{
NSLog(@"No");
你可以使用这样的代码:
NSString *dateString = @"01.01.1970";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd.MM.yyyy";
if ([dateFormatter dateFromString:dateString]) {
//YES
}
为什么NSDateFormatter
:它是为了解析日期而创建的。另外,通过这种方式,您可以轻松地更改日期格式,并且可以获得有效的NSDate
对象。
但是,如果您打算经常使用此dateFormatter
(例如,它在UITableViewCell
中使用),您可能会遇到性能问题。如果你这样做了,并且你确定NSDateFormatter
是导致它的原因(仪器可能会帮助你),你可以重复使用你的dateFormatter
。例如,像这样:
NSString *dateString = @"01.01.1970";
static NSDateFormatter *dateFormatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd.MM.yyyy";
});
if ([dateFormatter dateFromString:dateString]) {
//YES
}
似乎(根据我运行的测试,这是我的猜测)第一次调用dateFromString
会触发dateFormatter
内部的延迟初始化,并且需要一些时间(下面有几个测试结果)。如果重复使用它,NSDateFormatter
初始化只执行一次。
在iOS 8.4.1的iPhone 5S上,dispatch_once
版本的速度提高了大约10倍:
dispatch_once
:0.536秒,娱乐:5.475秒(解析10.000个日期的时间)
在同一测试中,@ zaph在iOS 6x的iPhone 6S上获得了2倍的性能差异:
dispatch_once
:0.57秒,娱乐:1.01秒(解析10.000个日期的时间)
因此,它取决于设备,操作系统版本以及您将如何密集地使用该dateFormatter。在某些情况下,第二个代码片段可能是一种过度杀伤力。但我遇到的情况是它提供了显着的性能提升。
UPD:还要注意的是,美国的日期也经常用点作为分隔符,所以看起来像是dd.MM.yyyy
日期可能实际上是MM.dd.yyyy
日期(例如4月5日而不是5月4日)。对于使用dd > 12
的日期,这不是问题,但不是问题。如果没有额外的背景,我认为没有什么可以做的,所以请注意。
您可以使用Regex进行检查。例如,此代码使用Regex检查“mm.dd.yyyy”:
NSError *error = NULL;
NSString *expForreg = @"^((((0[13578])|([13578])|(1[02]))[\\.](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\\.](([1-9])|([0-2][0-9])|(30)))|((2|02)[\\.](([1-9])|([0-2][0-9]))))[\\.]\\d{4}$|^\\d{4}$";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:expForreg
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:@"10.30.1989" options:0 range:NSMakeRange(0, [@"10.30.1989" length])];
if(matches && matches.count > 0)
{
NSLog(@"Ok");
}else
{
NSLog(@"No");
}
希望这有帮助!
您可以使用正则表达式:
NSString *testString = @"11.22.3333";
NSString *pattern = @"^\\d{2}\\.\\d{2}\\.\\d{4}$";
NSRange range = [testString rangeOfString:pattern options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
NSLog(@"Ok");
}
else{
NSLog(@"No");
}
这不是一个真正的日期测试。