How do I format a date from a string?

I have a line with this value:

2010-05-13 23:17:29

      

I would like to format it and use the following code:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterMediumStyle;
NSDate *formattedDate = [formatter dateFromString:dateString];
[formatter release];

      

When the debugger reaches the release line, formattedDate shows "invalid CFStringRef" and

Cannot access memory at address 0x0

      

Any ideas what I am doing wrong?

+2


a source to share


2 answers


dateFromString

returns nil

because it cannot parse the string containing the date and time. This is because it NSDateFormatterMediumStyle

specifies a date format such as May 16, 2010 (it really depends on locale and user preferences). This format doesn't match your string.

To parse your string, you must set dateFormat

instead dateStyle

, for example:



formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

      

+7


a source


Your line may have already been released.



I also suspect that your date string is not in the correct format for formatting, which will give you a zero date.

0


a source







All Articles