NSDateFormatter确实返回了预期的内容

时间:2011-06-25 22:46:43

标签: iphone objective-c nsdate formatter

我创建了一个从NSString返回NSDate的方法。代码如下。我发送到功能" 2/25/2011"。该函数返回" 2010-12-26 08:00:00 + 0000"

我做错了什么?我还需要在最后发布NSString。我该怎么做?

谢谢你!

-(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
  */  
}

3 个答案:

答案 0 :(得分:2)

您使用/分隔符传递了日期,但您指定了-作为日期格式化程序的分隔符。关于发布字符串的问题,您应该只发布您拥有的对象,即您使用newalloccopymutableCopy创建的对象。见下面的例子。

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

答案 1 :(得分:1)

您将格式设置为@"MM-dd-YYYY",但传入的字符串格式为@"1/1/1970"。那不匹配。见Data Formatting Guide: Date formatters


// how do I release dateFromString?

使用autorelease

return [dateFromString autorelease];

请参阅Memory management

答案 2 :(得分:1)

我遇到的问题是该格式在年内有CAP LETTERS。

这是正确的:

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

这是错误的:注意大写YYYY

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