从日期选择器获取日期到变量中的字符串

时间:2017-01-16 10:42:10

标签: ios swift datetime uidatepicker

我已制作并订购应用我已将outlet命名为selectedDate,我想将所选日期检索到变量。我应该在View中加载什么。

@IBOutlet weak var selectedDate: UIDatePicker!

func datePickerChanged(selectedDate:UIDatePicker) {
    var dateFormatter = DateFormatter()
    dateFormatter.dateStyle = DateFormatter.Style.FullStyle
    dateFormatter.timeStyle = DateFormatter.Style.FulltStyle
    var strDate = dateFormatter.string(from: selectedDate.date)  
} 

2 个答案:

答案 0 :(得分:4)

class ViewController: UIViewController {

@IBOutlet weak var datePicker: UIDatePicker!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
 @IBAction func datePickerChanged(sender: UIDatePicker) {

    print("print \(sender.date)")

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM dd, YYYY"
    let somedateString = dateFormatter.stringFromDate(sender.date)

    print(somedateString)  // "somedateString" is your string date
}


}

您必须为datePicker创建一个IBAction并将其命名为“datePickerChanged”,就像您创建对象的出口一样。选择连接类型"操作"当您将对象拖动到Viewcontroller时。

答案 1 :(得分:2)

func datePickerChanged(_:UIDatePicker)是目标函数。

您是否正确设置了目标?

// Precise that our controller implement the delegate
class MyViewController: UIViewController {
  ...
  @IBOutlet weak var selectedDate: UIDatePicker!
  ...
  override func viewDidLoad() {
    super.viewDidLoad()
    ...
    selectedDate.addTarget(self, action: #selector(datePickerChanged(_:)), forControlEvents: .valueChanged) // We register the target function
  }

  ...
  // We implement that function
  func datePickerChanged(sender:UIDatePicker) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .full
    dateFormatter.timeStyle = .full
    let strDate = dateFormatter.string(from: sender.date)  
    print(strDate)
  } 
}