Objective-C-NSDateFormatter返回错误的日期 [英] objective-c - NSDateFormatter returns wrong date

查看:53
本文介绍了Objective-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返回:

The first NSLog returns:

1 -2012年3月23日

1-March 23, 2012

第二个:

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

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

第三个:

2011年3月25日

3-25/12/2011

为什么从字符串中获取日期并设置日期格式会更改日期?我期望第三个NSLog(或dateCal)等于2012年3月3日。我住在英国,所以与时区无关。

Why does the date change when getting the date from the string and formatting it? I'm expecting the third NSLog (or dateCal) to equal 23/3/2012. I live in the UK so its not to do with the timezone..

谢谢,

Jack

推荐答案

需要在行中使用小写字母y:

Needed to use lower case 'y' in the line:

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

这篇关于Objective-C-NSDateFormatter返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆