【问题标题】:Converting A NSDate Array to a String Array in Swift在 Swift 中将 NSDate 数组转换为字符串数组
【发布时间】:2015-06-07 21:22:30
【问题描述】:

我对 swift 和 IOS 编码有点陌生。我有一个从解析“CreatedAt”列中检索到的 NSdate 数组。我需要将该数组转换为字符串数组,以便可以将其用作表格视图单元格中文本标签的输入。

//I try the below, I defined resultsDateArrayString as string array variable, and resultsDateArray as NSdate array variable.

      var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "hh:mm"
        resultsDateArrayString = dateFormatter.stringFromDate(self.resultsDateArray)

        cell.postDateTxt.text = self.resultsDateArrayString[indexPath.row]

【问题讨论】:

  • 您用 [nsdateformatter] 标记了您的问题,因此您似乎已经知道如何将日期转换为字符串...
  • 其实我试过了,但不能用数组实现。
  • 你尝试了什么? – self.resultsDateArray 是一个数组self.resultsDateArray[indexPath.row] 是该数组的一个元素,即 date ...现在获取该日期并将其转换为 string
  • 我更新了我正在尝试的内容

标签: string swift parse-platform nsdateformatter


【解决方案1】:

这是将日期格式化为String 的一种非常低效的方法,因为它每次都会实例化一个新的NSDateFormatter。考虑为该类创建一个常量NSDateFormatter 作为优化。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
    let formatter = NSDateFormatter()
    formatter.timeZone = NSTimeZone.systemTimeZone()
    formatter.dateStyle = .ShortStyle
    formatter.timeStyle = .ShortStyle
    cell.textLabel!.text = formatter.stringFromDate(resultsDateArray[indexPath.row])
    return cell
}

更新 1

要获得您在更新问题中提到的 hh:mm 格式,只需删除 formatter.dateStyle = .ShortStyle 行即可

【讨论】:

  • 您好 Kumuluzz,非常感谢您的回答。我更新为您的代码,但是当我运行时,我在以下部分收到错误“在展开可选值时意外发现 nil”:self.resultsDateArray.append(object.objectForKey("createdAt") as! NSDate) 为什么会发生这种情况?
  • 很可能是因为该特定对象没有“createdAt”属性。我建议安全地解开 objectForKey 的结果。类似于:if let date = object.objectForKey("createdAt") as! NSDate { self.resultsDateArray.append(date) }
  • 另一种选择是因为你还没有初始化你的resultsDateArray。你可以像这样初始化它:var resultsDateArray: [NSDate] = []
  • stackoverflow.com/questions/30487622/… 在这个链接中有一个类似的问题说使用 object.updatedAt 而不是 objectforkey("updatedAt") 但它也不起作用。顺便说一下,我已经初始化了数组。
  • 您是如何生成数据的?通过查询 Parse 后端?还是在本地创建它们?因为如果您在本地创建它们,那么它们的createdAt 属性为零。你必须把它保存在后端,它会自动设置这个值
【解决方案2】:

我会使用带有 NSDateFormatter 的 map 函数,以您想要的输出格式包裹每个日期。

var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = ...
var strings = dates.map{dateFormatter.stringFromDate($0)}

【讨论】:

    猜你喜欢
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 2016-01-27
    • 2015-04-16
    • 2016-07-13
    相关资源
    最近更新 更多