【问题标题】:Date value became null while using nadateformatter in uitableview cellForRowAtIndexPath method在 uitableview cellForRowAtIndexPath 方法中使用 nadateformatter 时,日期值变为空
【发布时间】:2014-04-19 07:08:14
【问题描述】:

我正在从服务器获取一组值,包括日期。当我在表格视图中显示日期时,我需要更改格式。所以这是我的数组:

{
    amount = "-651.5700"; 
    "date_added" = "2014-04-14 03:03:10";
    description = "Order Amount Paid ";
    "transaction_id" = 795;
},  {
    amount = "-1985.0700";
    "date_added" = "2014-04-14 03:03:10";
    description = "Order Amount Paid ";
    "transaction_id" = 794;
}  

我使用cellForRowAtIndexPath方法在表格视图中显示日期的代码是:

 NSString *str=[[[ArrDashboard objectAtIndex:indexPath.row] objectForKey:@"date_added"] copy];
  [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
  NSDate *date = [dateFormatter dateFromString:str];  
  [dateFormatter setDateFormat:@"MM/dd/yyyy"]; 
  NSString *strMyDate= [dateFormatter stringFromDate:date];
  cell.LblDate.text = [NSString stringWithFormat:@"%@",strMyDate];

我在数组中得到了许多值,但在转换其中一些值后,我得到空值,而一些是转换后的日期字符串。
如果有人可以提供帮助,将不胜感激。
谢谢。

【问题讨论】:

  • 对于哪些日期,您得到空值? - 对于 24 小时格式,第一个日期格式可能必须是“yyyy-MM-dd HH:mm:ss”和大写“HH”。
  • 嘿@MartinR!非常感谢。它现在工作正常。将甲酸盐更改为大写 HH 后。我现在没有得到空值。非常感谢。 :)
  • 你应该收藏Date Format Patterns page

标签: ios objective-c nsdateformatter mobile-application


【解决方案1】:
    NSString *str=[[[ArrDashboard objectAtIndex:indexPath.row] objectForKey:@"date_added"] copy]; 
   [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    NSDate *date = [dateFormatter dateFromString:str]; 
    [dateFormatter setDateFormat:@"MM/dd/yyyy"]; 
    NSString *strMyDate= [dateFormatter stringFromDate:date]; 
    cell.LblDate.text = [NSString stringWithFormat:@"%@",strMyDate];

您从响应中获取的日期格式错误

【讨论】:

    【解决方案2】:

    Alloc you dateformatter 试试这个代码是否完美

        NSString *str=@"2014-04-14 03:03:10";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:str];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSString *strMyDate= [dateFormatter stringFromDate:date];
    NSString *strResult = [NSString stringWithFormat:@"%@",strMyDate];
    

    【讨论】:

    • 哦?试试“2014-04-14 13:03:10”。
    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    相关资源
    最近更新 更多