对象-将字符串转换为NSDate?

时间:2018-08-27 00:26:17

标签: ios objective-c

我正在尝试将单元格UILabel中显示的文本转换为NSDate格式。由于某种原因,即使我的字符串(timeEnd)包含值,我的以下代码也无法正常工作? timeEnd的输出是:19-08-2018 17:38,但是由于某种原因,我的转换结果是(NULL)?

ViewController.m

NSString *timeEnd = filteredSwap[indexPath.row][@"endswaptime"];
cell.endTime.text = timeEnd;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM y hh:mm a zzz"];
NSLog(@"Date is: %@", [dateFormatter dateFromString:timeEnd]);

3 个答案:

答案 0 :(得分:1)

  

timeEnd的输出是:19-08-2018 17:38,但是由于某种原因我的转换结果是(NULL)?

您的字符串格式与您用于日期格式化程序的格式不匹配。 NSDateFormatter因此无法使用您指定的格式创建有效日期,并且返回nil

答案 1 :(得分:1)

使用以下代码获取日期:

  <?php 
   $q  = mysqli_query($con,"SELECT * FROM salary_logs 
   ORDER BY id ASC LIMIT 5");
    $result_array = array();
    while($row = mysqli_fetch_assoc($q))
   {
     $result_array[] = $row['month'];
     $result_array2[] = $row['salary'];
     echo json_encode($result_array, JSON_HEX_TAG);
   }
  ?>

答案 2 :(得分:0)

        NSString *timeString = @"01/03/2018";

        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
        NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
        [dateFormatter setTimeZone:timeZone];

        result = [dateFormatter dateFromString:timeString];