IOS:将NSDate转换为NSString给出nil值

时间:2013-05-14 08:58:04

标签: ios nsstring nsdate nsdateformatter

我的错误在哪里?我有一个这种格式的NSDate(数据:14/05/2013 10:52:27),我必须获得一个NSString。

   NSLog(@"Data: %@",lettureObj.data);

   NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
   [outputDateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
   NSString *data  = [outputDateFormatter stringFromDate:lettureObj.data];

3 个答案:

答案 0 :(得分:0)

使用以下功能

//*********************************Convert String into Date **********************

- (NSDate*) convertStringToDate:(NSString*)dateStr dateformat:(NSString*)dateformat
{
    // Convert string to date object
    //dateformat like :@"yyyy-MM-dd"]
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateformat];
    NSDate *date = [dateFormatter dateFromString:dateStr];  
    [dateFormatter release];//For NON-ARC
    return date;
}

//*********************************Convert date into String **********************

- (NSString*) convertDateToString:(NSDate*)date  dateformat:(NSString*)dateformat
{
    // Convert date object to desired output format
    NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
    [dateFormat1 setDateFormat:dateformat];
    NSString *dateStr = [dateFormat1 stringFromDate:date];  
    [dateFormat1 release];//For NON-ARC

    return dateStr;
}

希望它能帮到你

答案 1 :(得分:0)

这里的问题是lettureObj.data是NSString,你需要的是将它主要转换为日期以拥有一个NSDate对象

答案 2 :(得分:0)

试试这个

   NSString *strTemp = [NSString stringWithFormat:@"%@",lettureObj.data];

   NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
   [dateFormat setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
   NSDate *date = [dateFormat dateFromString:strTemp];
   [dateFormat release];


   NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
   [outputDateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];

  NSString *data  = [NSString stringWithFormat:@"%@",[outputDateFormatter stringFromDate:date]];