I have one string like this “2012 12 12 12:12”, how to format as a Date ?
I try this but not work
-(NSDate *)stringToDate:(NSString *)date
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
[formatter setTimeZone:timeZone];
[formatter setDateFormat : @"yyyy MM dd HH:mm"];
NSString *stringTime = date;
NSDate *dateTime = [formatter dateFromString:stringTime];
[formatter release];
return dateTime;
}
Update: when I change the position of formatter, it also can not work by:
NSLog(@"%@", stringToDate(@"2012 12 12 12:12"));
It outputs “null”, But it works with string format like “2012-12-12 12:12”
Change this,
to
Don’t release formatter until you are done with the use of it in converting from string to date. In your code, you are releasing it before the conversion itself.
Update:
You need to use it as,
You can not use
stringToDate(@"2012 12 12 12:12")in objective-c. Equivalent here is[self stringToDate:@"2012 12 12 12:12"].