ios - 来自 NSDateFormatter 的 NSDate

标签 ios nsdate nsdateformatter

我正在测试一些 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/

相关文章:

iphone - 检查NSDate是在本周还是下周

ios - window.location.href 在phonegap 中不起作用

ios - 将“NSDate”转换为“NSString”,例如@@“11:22 am”?

c# - UISearchBar 中的中心 UISegmentedControl

具有多个 sortDescriptors 和 Bool 过滤器的 Swift fetchRequest

ios - 将 NSString 解析为 NSDate

ios - 日期字符串 -> 字符串日期中断?

objective-c - NSDateFormatter setDateFormat 非零填充月份数

iOS Swift3 检查 ViewController 对象的 nil 值

ios - Xcode 解析带下划线的 JSON