首页 > 解决方案 > 从 Firebase 数据库检索后将字符串更改为日期时的值为 nil

问题描述

由于 Firebase 不允许您将其存储为 Date 数据类型,因此我已将 Date 值作为 String 存储在我的 Firebase 数据库中。这是数据库的屏幕截图:

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;我怎么解决这个问题?

标签: iosswiftfirebasedatefirebase-realtime-database

解决方案


在从字符串获取日期之前,您需要将日期格式设置为 dateformatter。假设您的截止日期 (10-22-2019 22:12) 是输入,dateFormat 将如下所示。

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"

推荐阅读