UIDatePicker问题 - 没有正确显示时间

时间:2017-06-22 18:44:57

标签: ios swift nsdateformatter

我想将用户从UIDatePicker中选取的时间保存到String类型的核心数据实体中(我只选择了String以适合下面的代码。在这里打开建议)。目的是稍后使用this code在选定的时间发送用户内部通知。

当用户选择 20:00 并点击保存按钮时,我希望显示20:00 。但是,它会显示:

<NSDateFormatter: 0x60000024f8a0>

在表的行中。每次添加时间,输出都如上所示,而不是显示的实际时间。我的目的只是存储时间,以便我可以向他们发送this等通知。

以下是按钮的代码:

@IBAction func addBobBtnTapped(_ sender: AnyObject)
    {
        let context =  (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext //creates an object of a property in AppDelegate.swift so we can access it

        let bob = Bob(context: context)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "hh:mm"
        dateFormatter.string(from: timeSetbyUser.date)

        bob.timeToPing = dateFormatter.description
            //timeSetbyUser.date as NSDate?

        //Save the data to core data
        (UIApplication.shared.delegate as! AppDelegate).saveContext()
        navigationController!.popViewController(animated: true)
    }

非常感谢!

1 个答案:

答案 0 :(得分:2)

您需要替换以下两行:

dateFormatter.string(from: timeSetbyUser.date)

bob.timeToPing = dateFormatter.description

使用:

bob.timeToPing = dateFormatter.string(from: timeSetbyUser.date)

不要忽略警告。您应该在线上看到警告:

dateFormatter.string(from: timeSetbyUser.date)

关于未使用的返回值。这是一个重要的线索。

您还应该更改日期格式。使用HH:mm 24小时或使用hh:mm a 12小时,上午/下午。

相关问题