DateFormatter没有输出错误的日期

时间:2012-03-01 22:23:20

标签: objective-c ios5 nsdateformatter

我正在尝试从字符串开始约会但是它总是在1月份制作日期...为什么?

代码:

NSMutableArray *dateArray = [NSMutableArray array];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYYMMDD"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

for (id <NSFetchedResultsSectionInfo> sectionInfo in [fetchedResultsController sections]) {
    NSLog(@"Adding date: %@", [sectionInfo name]);
    NSDate *newDate = [dateFormatter dateFromString:[sectionInfo name]];
    NSLog(@"Adding date 2: %@", newDate);
    [dateArray addObject:newDate];
}

日志:

2012-03-01 15:14:48.124 MyApp[21793:fb03] Adding date: 20120827
2012-03-01 15:14:48.124 MyApp[21793:fb03] Adding date 2: 2012-01-27 00:00:00 +0000
2012-03-01 15:14:48.125 MyApp[21793:fb03] Adding date: 20120830
2012-03-01 15:14:48.125 MyApp[21793:fb03] Adding date 2: 2012-01-30 00:00:00 +0000
2012-03-01 15:14:48.125 MyApp[21793:fb03] Adding date: 20120831
2012-03-01 15:14:48.126 MyApp[21793:fb03] Adding date 2: 2012-01-31 00:00:00 +0000
2012-03-01 15:14:48.126 MyApp[21793:fb03] Adding date: 20120906
2012-03-01 15:14:48.127 MyApp[21793:fb03] Adding date 2: 2012-01-06 00:00:00 +0000
2012-03-01 15:14:48.127 MyApp[21793:fb03] Adding date: 20120907
2012-03-01 15:14:48.128 MyApp[21793:fb03] Adding date 2: 2012-01-07 00:00:00 +0000
2012-03-01 15:14:48.128 MyApp[21793:fb03] Adding date: 20120910
2012-03-01 15:14:48.128 MyApp[21793:fb03] Adding date 2: 2012-01-10 00:00:00 +0000
2012-03-01 15:14:48.129 MyApp[21793:fb03] Adding date: 20120913
2012-03-01 15:14:48.129 MyApp[21793:fb03] Adding date 2: 2012-01-13 00:00:00 +0000

1 个答案:

答案 0 :(得分:3)

月份说明符的日期为dd,而不是DD。此外,您可能希望使用yyyy格式多年,因为YYYY表示ISO'年度周',并且可能与实际年份不同。所以你的最终格式应该是这样的:

[dateFormatter setDateFormat:@"yyyyMMdd"];