我希望有一种用户输入的方式"日期文本" (例如,3/3/1990或3-1-98)格式化为NSDate。
我可以自己尝试使用各种日期格式化程序来格式化文本,但我有一种潜在的怀疑,即有一种更简单的方法可以做到这一点。
dateWithNaturalLanguageString:可能会有效,但我听说有传言说这会引起应用商店的拒绝?
答案 0 :(得分:2)
您正在寻找NSDataDetector
并返回NSTextCheckingResult
个对象。
答案 1 :(得分:1)
我不确定这是否涵盖了您需要的所有内容,但NSDateFormatter
类有dateFromString:
方法。如果您能够识别字符串所处的格式并创建相应的NSDateFormatter
对象,那么这就行了。
答案 2 :(得分:0)
所以NSDataDetector是我的杯子o'茶,我在类方法中用一些内省的if-else语句来强制解决这个问题。如果未来土地上的任何人感兴趣:
#import "TotalStringToDateFormatter.h"
@implementation TotalStringToDateFormatter
+(NSDate*) convertString:(NSString *)string
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
NSDate* date;
NSString* checkString;
[dateFormatter setDateFormat:@"mm/dd/yyyy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"mm-dd-yyyy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"m/d/yyyy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"m-d-yyyy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"m/d/yy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"m-d-yy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"mm/d/yyyy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"mm-d-yyyy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"m/dd/yyyy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
[dateFormatter setDateFormat:@"m-dd-yyyy"];
date = [dateFormatter dateFromString:string];
checkString = [dateFormatter stringFromDate:date];
if ([string isEqualToString:checkString]) {
return date;
}
return nil;
}
@end
创建withLocale版本并不难,但我坦率地不太了解Locale是如何编码的,现在不需要它