ios - 从 Firebase 数据库检索后将字符串更改为日期时的值为 nil
问题描述
由于 Firebase 不允许您将其存储为 Date 数据类型,因此我已将 Date 值作为 String 存储在我的 Firebase 数据库中。这是数据库的屏幕截图:
数据的检索没有问题。检索后,我想将字符串转换为日期(“10-22-2019 22:12”),代码如下:
class CustomNotificationsTableCell: UITableViewCell {
var notificationTableCellData: NotificationsData? {
didSet {
let dateformatter = DateFormatter()
let deadline = dateformatter.date(from: notificationTableData.storyDeadline) // notificationTableData.storyDeadline is the date String
_ = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
let seconds = Int(deadline?.timeIntervalSinceNow ?? 0.0)
self.timeLeft.text = "\(seconds / 3600):\((seconds % 3600) / 60):\(seconds % 60)"
if seconds == 0 {
timer.invalidate()
}
}
}
}
}
问题是变量的值deadline
总是 nil;我怎么解决这个问题?
解决方案
在从字符串获取日期之前,您需要将日期格式设置为 dateformatter。假设您的截止日期 (10-22-2019 22:12) 是输入,dateFormat 将如下所示。
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
推荐阅读
- javascript - postMessage(...) 正在向 targetWindow 以外的窗口发布消息
- python - Python 字典列表:如何判断值是否不存在
- switch-statement - 为什么表达式:If (A:=!A) 每次按下热键时的计算结果都不同?
- regex - 如何使用 RE2 正则表达式匹配两个字符串之间的子字符串?
- c - 寻找最大的回文数
- javascript - 从字符串数组中过滤对象数组
- powershell - $PSCmdlet.ShouldProcess 状态在调用之间存储在哪里(以及如何重置)?
- node.js - 如何修复“内容安全策略:页面设置阻止在 http://localhost:8080/favicon.ico(“default-src”)加载资源。
- owl - 猫头鹰形式语义
- mysql - Json extract - 脚本无法仅提取其中一个字段