使用DatePicker和TextField时将String转换为NSDate

时间:2015-05-26 18:20:30

标签: ios swift datepicker

我正在使用使用datePicker而不是键盘的文本字段。它显示格式为字符串,看起来像'2015年5月31日12:30'(取自println(delivery.text)函数。)我想将日期更改为NSDate,因此我可以与当前日期进行比较。有什么建议吗?

@IBOutlet weak var pickUp: UITextField!
@IBOutlet weak var delivery: UITextField!
let dateFormat: NSDateFormatter = NSDateFormatter()
let datePicker: UIDatePicker = UIDatePicker()
let dateFormat2: NSDateFormatter = NSDateFormatter()
let datePicker2: UIDatePicker = UIDatePicker()


override func viewDidLoad() {
    super.viewDidLoad()
    dateFormat.dateStyle = NSDateFormatterStyle.LongStyle
    dateFormat.timeStyle = NSDateFormatterStyle.LongStyle
    datePicker.datePickerMode = UIDatePickerMode.DateAndTime
    datePicker.addTarget(self, action: Selector("updateDateField:"), forControlEvents:UIControlEvents.ValueChanged)

    pickUp.inputView = datePicker

    dateFormat2.dateStyle = NSDateFormatterStyle.LongStyle
    dateFormat2.timeStyle = NSDateFormatterStyle.LongStyle
    datePicker2.datePickerMode = UIDatePickerMode.DateAndTime
    datePicker2.addTarget(self, action: Selector("updateDateField:"), forControlEvents:UIControlEvents.ValueChanged)
    delivery.inputView = datePicker2


    // Do any additional setup after loading the view.
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.toolbarHidden = false
    self.tabBarController?.tabBar.hidden = true
}

func updateDateField(sender: UIDatePicker) {
    if sender == datePicker
    {
        pickUp.text = dateFormat.stringFromDate(sender.date)
    }
    if sender == datePicker2
    {
        delivery.text = dateFormat2.stringFromDate(sender.date)
    }


}

2 个答案:

答案 0 :(得分:2)

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy 'at' h:mm:ss a"
if let date = dateFormatter.dateFromString("May 31, 2015 at 12:30:15 PM") {
  println(date)
}

如果你需要一些日期格式参考,你可以使用这个:

enter image description here

答案 1 :(得分:1)

您可以尝试使用DateFormatter将字符串格式化为日期,然后像这样拉出NSDate对象。在你的情况下,这样的事情可能会满足你的需求。

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM d, yyyy at H:mm"
let date = dateFormatter.dateFromString(//insert string here)

如果您有其他问题,请参阅original documentation或格式指南handy guide