如何将日期字符串转换为字符串(yyyy-MM-dd)。这样做,我得到空值?

时间:2010-04-30 06:33:16

标签: cocoa nsdate nsdateformatter

我的数据为customerFromDate“2010年4月1日”和customerToDate“2010年4月30日”,这是一个字符串。

我想将该格式转换为字符串“yyyy-MM-dd”,但是这样做时我得到了空值。 请参阅我尝试过的以下代码。

printf("\n customerFromDate %s",[customerStatementObj.customerFromDate UTF8String]);
printf("\n customerToDate %s",[customerStatementObj.customerToDate UTF8String]);
/*
 prints as the following 
 customerFromDate 01 Apr 2010
 customerToDate 30 Apr 2010
 */

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *fromDate=[[NSDate alloc]init];
fromDate = [dateFormatter dateFromString:customerStatementObj.customerFromDate];
printf("\n fromDate: %s",[fromDate.description UTF8String]);
NSString *fromDateString=[dateFormatter stringFromDate:fromDate];
printf("\n fromDateString: %s",[fromDateString UTF8String]);    
[dateFormatter release];

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
[dateFormatter1 setDateFormat:@"yyyy-MM-dd"];
NSDate *toDate=[[NSDate alloc]init];
toDate = [dateFormatter1 dateFromString:customerStatementObj.customerToDate];
printf("\n toDate: %s",[toDate.description UTF8String]);
NSString *toDateString=[dateFormatter1 stringFromDate:toDate];
printf("\n toDateString: %s",[toDateString UTF8String]);            
[dateFormatter1 release];

谢谢你, Madan Mohan。

1 个答案:

答案 0 :(得分:4)

几点说明:

您需要两个不同的NSDateFormatters。一个指定输入日期格式,另一个指定输出日期格式。

    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"dd MMM yyyy"];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"yyyy-MM-dd"];

您可以为fromDatetoDate重复使用这些格式化程序。

其次,dateFromString:返回已分配的自动释放的NSDate对象。您正在泄漏手动分配的那些。

#import <Cocoa/Cocoa.h>

int main (int argc, char const *argv[])
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"dd MMM yyyy"];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"yyyy-MM-dd"];

    NSDate *fromDate = [inputFormatter dateFromString:@"01 Apr 2010"];
    NSDate *toDate = [inputFormatter dateFromString:@"30 Apr 2010"];

    printf("\n fromDate: %s",[fromDate.description UTF8String]);
    NSString *fromDateString=[outputFormatter stringFromDate:fromDate];
    printf("\n fromDateString: %s",[fromDateString UTF8String]);

    printf("\n toDate: %s",[toDate.description UTF8String]);
    NSString *toDateString=[outputFormatter stringFromDate:toDate];
    printf("\n toDateString: %s",[toDateString UTF8String]);

    [inputFormatter release];
    [outputFormatter release];

    [pool drain];
    return 0;
}