-5

I want to get the data from a UIDatePicker and convert that data into a String variable so I can later display that value in a label. I am making a program to display a users meal in a table. I am using Swift and would like thorough instructions as I am fairly new. Thanks!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
b mmm
  • 11
  • 5
  • 1
    duplicate: http://stackoverflow.com/questions/11866712/observing-change-in-uidatepicker – Joe Daniels Dec 15 '16 at 00:28
  • but it doesnt tell me how to convert the data into a string! – b mmm Dec 15 '16 at 00:43
  • 1
    @bmmm As with all programming, it's a matter of breaking things down into small pieces. That link shows you how to get the value as a `Date`/`NSDate`, so then you just need a way of converting the `Date`/`NSDate` to a `String`. – Alexander Dec 15 '16 at 01:45

1 Answers1

0

Add a handler for your UIDatePicker like so:

yourDatePickerView.addTarget(self, action: Selector("handler:"), for: .valueChanged)

And then do something like this in your handler:

func handler(sender: UIDatePicker) {
    var timeFormatter = NSDateFormatter()
    timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

    var strDate = timeFormatter.stringFromDate(datePicker.date)
    // do what you want to do with the string.

    // alternate example:
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "US_en")
    formatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
    let date = formatter.date(from: "Thu, 04 Sep 2014 10:50:12 +0000")
}

Sources for these answers: How to get data from UIDatePicker - Swift

From String to NSDate in Swift

Community
  • 1
  • 1
Joe Daniels
  • 1,646
  • 1
  • 11
  • 9