是否可以为日期设置多个“setDateStyle”?像“NSDateFormatterShortStyle,NSDateFormatterMediumStyle”一样,因为我需要同时输入两种类型的日期并需要接受两种类型。可能吗?

最佳答案

您可以尝试将NSDataDetectorNSTextCheckingTypeDate一起使用,该格式可以识别许多日期格式。

NSString *dateText = @"march 31, 1945 12:34 pm";

NSError *error;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];
NSTextCheckingResult *result = [detector firstMatchInString:dateText options:0 range:NSMakeRange(0, dateText.length)];
NSDate *date = result.date;

NSString *reformattedDate = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterFullStyle];
NSLog(@"reformattedDate: %@", reformattedDate);

NSLog输出:

重新格式化日期:1945年3月31日,星期六,下午12:34:00

10-07 19:56
查看更多