NSDate、NSDateFormatter 的奇怪行为

Weird behavior of NSDate, NSDateFormatter

我正在我的应用程序中格式化 NSDate。使用以下代码:

    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    NSString* currentDateTime = [dateFormatter stringFromDate:now];

    NSLog(@"CurrentDateTime:%@", currentDateTime);

    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    currentDateTime = [dateFormatter stringFromDate:now];
    NSLog(@"CurrentDateTime 1 :%@", currentDateTime);

    [dateFormatter release];

但这全年都可以正常工作,但在 12 月 27 日之后失败。它在格式为 27-Dec 或以上的日期后添加一年。只有当我们使用 "YYYY" 而不是 "yyyy" 时。年份变化后它再次正常工作。那么,请问您能否提出这背后的原因。

我对你问题的回答如下

"YYYY" is week-based calendar year.

"yyyy" is ordinary calendar year.

了解更多详情

Difference between 'yyyy' and 'YYYY'

Unicode Standard