我正在测试一些 dateFormatter,我有一个简单的问题
formatter :
- (void)testDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
[dateFormatter setLocale:locale];
NSString *stringDate = @"23/03/1";
NSDate *date = [dateFormatter dateFromString:stringDate];
XCTAssertTrue(date == nil);
}
我的测试是红色的,因为日期不是零。当我打印日期时:
(lldb) po date
0001-03-22 23:50:39 +0000
NSDateFormatter 正在填充日期字符串 (1 ----> 0001)。我不需要这个填充。您认为这是 NSDateFormatter 的正确行为吗? (这是 NSDateFormatter 类中的错误吗?)。我怎样才能避免这种情况?
谢谢
最佳答案
我认为对于为什么 @"23/03/1"
被认为是格式为 @"dd/MM/yyyy"< 的有效日期没有很好的答案
。这就是它的工作原理。但是如果你想测试它是否是 ##/##/####
格式,你可以这样做:
NSRange range = [stringDate rangeOfString:@"^\\d{2}/\\d{2}/\\d{4}$" options:NSRegularExpressionSearch];
XCTAssert(range.location == NSNotFound, @"Not in ##/##/#### format");
很明显,您必须将它与 NSDateFormatter
测试结合起来以确保这些值也合理,但以上将测试位数。
关于ios - 来自 NSDateFormatter 的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32209686/