简体   繁体   中英

NSDateFormatter does return what is expected

I created a method to return the NSDate from a NSString. Code is below. I send to the function "2/25/2011". The function returns "2010-12-26 08:00:00 +0000"

What did I do wrong? Also the NSString I need to release at the end. How do I do that?

thank you!

-(NSDate *) GetDatefromString:(NSString *) Str
{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setDateFormat:@"MM-dd-YYYY"];

    NSDate *dateFromString;
            // = [[NSDate alloc] init]; tried taking this part out but still not working


    if (Str != NULL)
    {
        dateFromString = [formatter dateFromString:Str];

    }
    else
    {
        dateFromString = [formatter dateFromString:@"1/1/1970"];
    }

    [formatter release];

     return dateFromString;    

// how do I release dateFromString?

  /*  
    Printing description of dateFromString:
    2010-12-26 08:00:00 +0000
    Printing description of Str:
    02-25-2011
  */  
}

You are passing in a date using the / seperator but you specified - as a separator for your date formatter. As to your question on releasing the string, you should only release objects that you own, ie that you have created with new , alloc , copy , or mutableCopy . See examples below.

NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; // needs releasing
[formatter setDateFormat:@"MM-dd-yyyy"];

NSString* str1 = @"06/25/2011"; // does not need releasing
NSString* str2 = [[NSString alloc] initWithString:@"06-25-2011"]; // needs releasing

NSDate* date1 =  [formatter dateFromString:str1]; // does not need releasing
NSDate* date2 =  [[NSDate alloc] init]; // needs releasing
date2 = [formatter dateFromString:str2]; 

NSLog(@"date from %@ : %@", str1, date1);
NSLog(@"date from %@ : %@", str2, date2);

// release the objects you own
[formatter release];
[str2 release];
[date2 release];

// prints out
date from 06/25/2011 : (null)
date from 06-25-2011 : 2011-06-25 00:00:00 -0700

you set the format to @"MM-dd-YYYY" but the string you pass in has the form @"1/1/1970" . That doesn't match. see Data Formatting Guide: Date formatters .


// how do I release dateFromString?

With autorelease .

return [dateFromString autorelease];

See Memory management .

The problem I had was the format had CAP LETTERS for the YEAR.

This is correct:

 [formatter setDateFormat:@"MM/dd/yyyy"];

And this is wrong: NOTE THE CAPS YYYY

[formatter
setDateFormat:@"MM-dd-YYYY"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM