Search code examples
swiftnsdatepicker

Get Hours and Minutes from NSDatePicker - Swift


Hi so i making something where a user enters a TIME into NSDatePicker so i can get the value and store it into a string for later use. I have connected the date picker with an outlet and im trying to get the value to export with no luck! Please help!

The NSDatePicker is setup to only show time like this 12:00 am

thanks


Solution

  • You need to get date property from Date Picker and use it together with NSCalendar to extract information.

    Try something like this piece of code

    func getHourFromDatePicker(datePicker:UIDatePicker) -> String
    {
        let date = datePicker.date
    
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute] , fromDate: date)
    
        return "\(components.hour):\(components.minute)"
    }
    

    And then, invoke it as follow:

    var strTime = getHourFromDatePicker(myDatePicker)
    print(strTime)