Learn Courses My Dashboard

Get Data from Date Picker

In my (mediocre at best) app, I can take 2 text fields, and store them to core data. But one of them should be a date.

I’d like to use date picker to replace the 2nd text field, but everything I’ve tried doesn’t seem to let me get it’s value so I can use it. When the user pics a date, how do I pass that to a variable? thanks!

  @objc private func didTapAdd() {
        let getInfo = UIAlertController(
            title: "Event Name & Date",
            message: "",
            preferredStyle: .alert
        //add fields
        getInfo.addTextField { field in
            field.placeholder = "Event Name"
            field.returnKeyType = .next
        let datePicker:UIDatePicker = UIDatePicker()
        datePicker.datePickerMode = .date
        getInfo.addTextField { field in
            field.placeholder = "Event Date MM/DD/YYYY"
            field.returnKeyType = .continue
 //       getInfo.addTextField { field in
//          field.placeholder = "Event Repeats"
//            field.returnKeyType = .continue
//        }
        //Add buttons
        getInfo.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        getInfo.addAction(UIAlertAction(title: "Continue", style: .default, handler:{ _ in
   //     print("Pop up was closed via Continue")
        //Read values
        guard let fields = getInfo.textFields, fields.count == 2 else {return}
        let eventName = fields[0]
        let eventDate = fields[1]
 //     let eventRepeats = fields[2]
            guard let eventName = eventName.text, !eventName.isEmpty,
                  let eventDate = eventDate.text, !eventDate.isEmpty else {
                      print("Invalid Entries, No Data Saved")

            //Convert eventDate String to Date until I can program date picker
            let dateString = eventDate
            let dateFormatter = DateFormatter()
            dateFormatter.locale = Locale(identifier: "en_US_POSIX")
            dateFormatter.dateFormat = "MM/dd/yyyy"
            if let eventDate = dateFormatter.date(from: dateString) {

            //    print(eventDate)
                  self.createItem(name: eventName, eventDate: eventDate)
        } ))
        present(getInfo, animated: true)

UIDatePicker uses the target-action pattern, so when you create one, you have to use addTarget(_:action:for:) to assign one of your functions that will get called.

So if you have this function:

private func userSelectedDate(_ sender: UIDatePicker) {
    //sender.date would contain the date selected by the user

you would set it up like this:

//I use ViewController here but you would use whatever
//your UIViewController is actually named
                     action: #selector(ViewController.userSelectedDate), 
                     for: .valueChanged)

Cool beans. I have the date outputting to print now, and I’ll get it in the code.

Then I can remove the 2nd text field, and maybe align this stuff better in the UI

Thanks again!

since i’m only working with date and not time for my displays, I was having some odd formatting where the last character was getting cut off

Nov 19, 2021 vs. Nov 19, 202

Took me a bit to figure it out.

I was removing 12 characters from the right for each. The difference? The string could be 1 char longer based on what time the date was selected

I output some stuff to console to figure it out.

Event Date String: Nov 19, 2021 at 3:31 PM
Event Date String: Nov 19, 2021 at 12:00 AM

so, I added just 1 line to your picker code to force the 12:00 AM standard, so I could display how I wanted.

thanks again

unless I can do it on one line. (now I feel fancy).

pickedDate = sender.date.startOfDay

    public func userSelectedDate(_ sender: UIDatePicker) {
        //sender.date contains the date selected by the user
            pickedDate = sender.date
            pickedDate = pickedDate.startOfDay

You should not be displaying Dates to the user by chopping up the date string. You should use a formatter; that’s what they are for. Formatters take care of the nitty-gritty details that are easy to get wrong. Formatters handle localization and user preferences for how to display dates. Formatters keep you from having to do exactly what you did here: count characters to make sure you are chopping off only what you want to chop off.

let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateStyle = .medium
formatter.timeStyle = .none
print(formatter.string(from: date))
//Nov 18, 2021

Use the tools the system gives us, don’t do things manually that don’t need to or shouldn’t be done manually.

that is good info. I was using that chunk of code for another part, however I didn’t know about the

formatter.timeStyle = .none


I’ll redo this, and drop the removeLast(12)