如何从字符串中获取日期(iPhone)?

如何从字符串中获取日期(iPhone)?,iphone,string,nsdateformatter,date-format,Iphone,String,Nsdateformatter,Date Format,当然,搜索比询问更容易 您可以使用带有以下代码的NSDateFormatter将包含日期的NSString转换为NSDate: I need to convert this string in to the date: 02-09-2011 20:54:18 I am trying the `dateFromString` method but every time it is returning (null), what NSDateFormatter should I use?,

当然,搜索比询问更容易


您可以使用带有以下代码的NSDateFormatter将包含日期的NSString转换为NSDate:

I need to convert this string in to the date:

    02-09-2011 20:54:18

I am trying the `dateFromString` method but every time it is returning (null), what NSDateFormatter should I use?, I have tried
`[formatter setDateFormat:@"yyyy-MM-dd"]` and `[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]`.


Here is my code:
NSString *finalDate = @"02-09-2011 20:54:18";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];

NSDate *dateString = [formatter dateFromString:finalDate];
NSLog(@"%@",dateString);


Thanks.

有一段时间,我认为这是一个关于“大冶形式”的计算机科学问题。。。你让我失望了:(没有人能生成Daye表单字符串。为什么你要设置两次日期格式。给出解决方案的代码你肯定会犯一些愚蠢的错误。为什么不在出现问题的地方给出一些代码呢?并且在不同的情况下也会有所不同。非常感谢,你的答案正是我在寻找的,我期待着日期格式出现错误,我搜索了一个lot以获取正确的日期格式,但没有再次得到感谢:-)将字符串转换为日期对象将返回GMT(格林威治标准时间)格式的日期。
// Your date as a string
NSString *finalDate = @"02-09-2011 20:54:18";

// Prepare an NSDateFormatter to convert to and from the string representation
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// ...using a date format corresponding to your date
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];

// Parse the string representation of the date
NSDate *date = [dateFormatter dateFromString:finalDate];

// Write the date back out using the same format
NSLog(@"Month %@",[dateFormatter stringFromDate:date]);