将字符串MM / DD / YYYY转换为NSDate

时间:2012-08-26 12:02:56

标签: iphone objective-c ios nsdate

在我的应用程序中,我正在使用Facebook Graph API,当我获取用户详细信息时,我将用户的生日作为格式为MM / DD / YYYY的字符串。

我的问题是,如何将字符串“MM / DD / YYYY”转换为NSDate

我尝试做

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"MM/DD/YYYY"];
 NSDate *date = [dateFormatter dateFromString:@"08/08/2012"];
 [dateFormatter release];  

但我得错了日期

4 个答案:

答案 0 :(得分:14)

使用NSDateFormatter,您可以直接从NSString转换为NSDate。这是一个例子:

NSDateFormatter* myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate* myDate = [myFormatter dateFromString:@"8/26/2012"];
NSLog(@"%@", myDate);

有关日期格式设置模式的详细信息,请参阅Unicode.org

答案 1 :(得分:5)

添加[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]

答案 2 :(得分:3)

你做得很好。您的问题只是格式字符串。

  • 资本M是月。
  • d是白天。
  • y是年份。

只要一致地使用这些符号就可以了。

答案 3 :(得分:1)

对于这种情况NSDateFormatter exist