views:

18

answers:

2

I need to show a date in a certain format on screen, but I need to store the date as a string in another format. I think this means I have to convert it to a date and back to a string.

How do i do this ?

I have already figured out how to convert my string to a date, however build analyser gives me a warning.

I want to convert the string from dd MM yyyy to yyyy-MM-dd

He my code so far...

NSString *startDateString = btnStartDate.titleLabel.text;
NSDateFormatter *dateStartFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateStartFormatter setDateFormat:@"dd MM yyyy"];
NSDate *datStartDate = [[NSDate alloc] init];
datStartDate = [dateStartFormatter dateFromString:startDateString];

alt text

+1  A: 

Well you're allocating space for datStartDate for a new NSDate, then replacing it with a completely new NSDate from your date formater (now you have memory set aside for the first NSDate that is never going to be used)

Use this:

NSDate* datStartDate = [dateStartFormater dateFromString:startDateString];

then use your dateStartFormater or another NSDateFormatter to turn your date into the required string like so:

 [dateStartFormatter setDateFormat:@"yyyy MM dd"];
 NSString* formatedDate = [dateStartFormater stringFromDate:datStartDate];
PostMan
I must be doing something wrong I get null http://img.skitch.com/20101001-gapu4pw1x8w3n1g1qugikfbegc.jpg
Jules
You have '-'s in your before date? Don't think that would make a difference though.
PostMan
IF you debug, what is inside datStartDate?
PostMan
My guess is that `startDateString` cannot be parsed by `dateFromString:` and that you get nil in return.
DarkDust
+1  A: 

The analyzer warns you of a leak. First, you assign a new object to datStartDate, and then you store a new value with datStartDate = [dateStartFormatter dateFromString:startDateString]; without releasing the previous object first.

So instead of:

NSDate *datStartDate = [[NSDate alloc] init];
datStartDate = [dateStartFormatter dateFromString:startDateString];

You should just write:

NSDate *datStartDate = [dateStartFormatter dateFromString:startDateString];
DarkDust
I'm not sure how this would work as you haven't specified yyyy-MM-dd ?
Jules
Look closely, it's about the `datStartDate` variable, that is the 4th line in your example. That creates a memory leak, as you overwrite the pointer from line 4 with a new object in line 5. The format is set in line 3, so everything is fine. Just try it: replace line 4 and 5 with the line I've proposed and the warning will be gone.
DarkDust