我有一个 json 文件正在导入我的项目 ( https://api.myjson.com/bins/ywv0k )。 json 属性被解码并存储在我的结构类“新闻”中,它具有与 json 文件相同的属性。
在第二步中,我用我的结构类“News”中的字符串属性“timestamp”填充了一个表,这实际上是一个 UNIX 时间。
我现在的问题是我不知道如何将这个 UNIX 时间更改为格式为“dd/mm/yy HH:mm:ss”的字符串,因为当我尝试放置一个函数时出现错误
let date = NSDate(timeIntervalSince1970: timestamp) //error since timestamp is currently defined as string. If I make it a long variable, I cannot populate the table with it any more, since the label requires a text with string format.
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "dd/mm/yy HH:mm:ss"
let dateString = dayTimePeriodFormatter.stringFromDate(date)
进入 do-encoding-loop 以及当我将其放入此表函数时:func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell。
swift 4
import UIKit
// structure from json file
struct News: Codable{
let type: String
let timestamp: String // UNIX format, eg. "1531294146340"
let title: String
let message: String
}
class HomeVC: BaseViewController, UITableViewDelegate, UITableViewDataSource {
var myNewsItems: [News] = []
@IBOutlet weak var myNewTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let nibName = UINib(nibName: "CustomTableViewCell", bundle: nil)
myNewTableView.register(nibName, forCellReuseIdentifier: "tableViewCell")
// JSON Decoding
let url=URL(string:"https://api.myjson.com/bins/ywv0k")
let session = URLSession.shared
let task = session.dataTask(with: url!) { (data, response, error) in
guard let data = data else { return }
do {
let myNewsS = try
JSONDecoder().decode([News].self, from: data)
print(myNewsS)
self.myNewsItems = myNewsS
DispatchQueue.main.async {
self.myNewTableView.reloadData()
}
} catch let jsonErr {
}
}
task.resume()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myNewsItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as!
CustomTableViewCell
// populate table with json content
cell.commonInit(timestamp: myNewsItems[indexPath.row].timestamp, message: myNewsItems[indexPath.row].message)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor(white: 1, alpha: 0.5)
}
}
最佳答案
首先日期格式不对。它必须是 "dd/MM/yy HH:mm:ss"
最有效的解决方案——如果您负责 JSON——将 timestamp
的值作为 Double
发送。然后声明 timestamp
let timestamp: Date // UNIX format, eg. 1531294146340
并添加日期解码策略
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .millisecondsSince1970
另一种解决方案是将日期转换代码放入结构中
struct News: Codable{
let type: String
let timestamp: String // UNIX format, eg. "1531294146340"
let title: String
let message: String
enum CodingKeys: String, CodingKey { case type, timestamp, title, message}
let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yy HH:mm:ss"
return formatter
}()
var dateString : String {
let timeInterval = TimeInterval(timestamp)!
let date = Date(timeIntervalSince1970: timeInterval / 1000)
return dateFormatter.string(from:date)
}
}
计算属性 dateString
包含日期字符串。
此外,您可以将 type
声明为枚举
enum Type : String, Codable {
case organizational, planning
}
struct News: Codable{
let type: Type
...
关于ios - 将 UNIX 时间从 json 导入(swift 结构)转换为日期作为字符串并填充表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873532/