在 Swift 中将 NSDate 数组转换为字符串数组
Converting A NSDate Array to a String Array in Swift
我对 swift 和 IOS 编码有点陌生。我有一个 NSdate 数组,它是从 parse "CreatedAt" 列中检索到的。我需要将该数组转换为字符串数组,以便我可以将其用作 tableview 单元格中文本标签的输入。
//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 将每个日期包裹起来,并输出您想要的格式。
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = ...
var strings = dates.map{dateFormatter.stringFromDate([=10=])}
这是一种将日期格式化为 String
的非常低效的方法,因为它每次都会实例化一个新的 NSDateFormatter
。考虑为 class 创建常量 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
我对 swift 和 IOS 编码有点陌生。我有一个 NSdate 数组,它是从 parse "CreatedAt" 列中检索到的。我需要将该数组转换为字符串数组,以便我可以将其用作 tableview 单元格中文本标签的输入。
//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 将每个日期包裹起来,并输出您想要的格式。
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = ...
var strings = dates.map{dateFormatter.stringFromDate([=10=])}
这是一种将日期格式化为 String
的非常低效的方法,因为它每次都会实例化一个新的 NSDateFormatter
。考虑为 class 创建常量 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