2012-03-23 61 views
0

我有这样一段代码:目标c - NSDateFormatter返回错误的日期

// Convert string to date object 
     NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
     [dateFormat setDateFormat:@"MMMM d, YYYY"]; 
     NSDate *formatDate = [dateFormat dateFromString:self.date]; 
     NSLog(@"1-%@", self.date); 
     NSLog(@"2-%@", formatDate); 
     NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:formatDate]; 
     NSString *dateCal = [NSString stringWithFormat:@"%d/%d/%d", [components day], [components month], [components year]]; 
     NSLog(@"3-%@", dateCal); 
     milage.date = dateCal; 

第一的NSLog返回:

1-2012年3月23日

第二种:

2-2011-12-25 00:00:00 +0000

第三个:

3-25/12/2011

为什么从字符串获取日期并格式化日期时会发生变化?我期待第三次NSLog(或dateCal)等于23/3/2012。我住在英国所以它不是做的时区..

感谢,

杰克

+1

我很惊讶,你看 “2012年3月23日,” 当你的NSLog self.date。在我的机器上,NSLog(@“%@”,[NSDate date]);产生一个像“2012-03-23 14:47:48 +0000”的日期。 – danh 2012-03-23 14:50:13

+2

谢谢,只需要使用'yyyy'代替。 – 2012-03-23 14:51:25

+0

这是一个测试,看看这个条件是否成立[self.date timeIntervalSinceReferenceDate] == [formatDate timeIntervalSinceReferenceDate]。 (丑陋的格式,很抱歉,但由于这不是一个真正的答案,我想它应该是一个评论)。 – danh 2012-03-23 14:52:34

回答

3

需要行使用小写字母 'Y':

[dateFormat setDateFormat:@"MMMM d, YYYY"]; 
+0

为什么大写'YYYY'会导致错误的一年? – 2014-09-03 15:37:21

2

你使用的setLocale方法是什么?

此外,从技术答疑&答:

如果您正在使用用户可见的日工作时,应避免设置一个日期格式字符串,因为它是很难预测你的格式字符串将如何以所有可能的用户配置表示。相反,您应该尝试限制自己设置日期和时间样式(通过 - [NSDateFormatter setDateStyle:]和 - [NSDateFormatter setTimeStyle:])。

0

使用[dateFormat setDateStyle:NSDateFormatterLongStyle];
而不是[dateFormat setDateFormat:@"MMMM d, YYYY"];
会给你,只要我找到它的理由。