我想知道如何计算两天之间的差异,然后将其显示在Swift 4中的标签上。我不知道为什么它不显示任何内容。这是我到目前为止的代码:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
var date = UserDefaults.standard.string(forKey: “date”) ?? “”
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = “mm/dd/yyyy”
var todaysDate = Date()
var futureDate = dateFormatter.date(from: date)
var diffinDays = Calendar.current.dateComponents([.day], from: todaysDate, to: futureDate!)
self.label.text = “\(diffinDays)”
请分享您对可能存在问题的想法。谢谢!
更新
代码在修订后仍然无法正常工作,而且最重要的是,我无法打印var diffinDays。我唯一能想到的是,我并不是从技术上运行Swift 4,而是在运行Swift 5 beta,但是大多数代码都可以运行并且脚本中没有错误。这是修改后的代码:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
var date = UserDefaults.standard.string(forKey: “date”) ?? “”
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = “MM/dd/yyyy”
var todaysDate = Date()
var futureDate = dateFormatter.date(from: date)
var diffinDays = Calendar.current.dateComponents([.day], from: todaysDate, to: futureDate!)
self.label.text = “\(String(describing: diffinDays.day))”
}
答案 0 :(得分:4)
缺少.day
,您可以尝试
self.label.text = "\(diffinDays.day)"