Has
Has

Reputation: 885

UIDatePicker problems - not displaying time correctly

I want to save the time that the user picks from UIDatePicker into a core data entity of type String (I just picked String to fit the code below. Open for suggestions here). The intention is to use this code later on to send the user internal notifications at the time selected.

When the user selects 20:00 and hits the save button, I want 20:00 to be displayed. However instead, it displays :

<NSDateFormatter: 0x60000024f8a0>

in the rows of the table. Everytime a time is added, the output is like above, instead of the actual time being displayed. My aim is just to store the time so I can send them notifications like this.

Here is the code of the button :

@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)
    }

Many thanks!

Upvotes: 0

Views: 39

Answers (1)

rmaddy
rmaddy

Reputation: 318934

You need to replace the following two lines:

dateFormatter.string(from: timeSetbyUser.date)

bob.timeToPing = dateFormatter.description

with:

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

Do not ignore warnings. You should be seeing a warning on the line:

dateFormatter.string(from: timeSetbyUser.date)

about the return value being unused. That's an important clue.

You should also change the date format. Either use HH:mm for 24-hour time or use hh:mm a for 12-hour time with am/pm.

Upvotes: 2

Related Questions