Search code examples
iosswift

Get date from date picker in swift


I have created an IBOutlet to a date picker.

@IBOutlet weak var logDate: UIDatePicker!

I have also set the mode of this date picker to date.

Is there a way for me to extract the date that the user would input into the date picker?

I tried using print(logdate), however it also gives me the date along with the time. Like this 2015-10-30 07:10:03 +0000


Solution

  • You can extract the date inputted by the user in a date field using this code. Note: This solution extracts the input as a string

        var dateFormatter = NSDateFormatter()
    
        dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle   // You can also use Long, Medium and No style.
        dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle   
    
        var inputDate = dateFormatter.stringFromDate(*datepicker outlet name*.date)
        print(inputDate)
    

    Used a section of code from: http://www.ioscreator.com/tutorials/display-date-date-picker-ios8-swift