简体   繁体   中英

My dateFormatter.dateFromString method always returns nil iOS Swift

I am trying to update a label to say whether or not if today's date is earlier or later than a date that came from a date picker. Pretty simple I thought but I can't figure out why my dateFromString method always returns nil. Because of that, I can't move forward. Any help explaining why this is, is very much appreciated!

let dataString = expirationField.text!
let dateFormatter = NSDateFormatter()
let expiringTime = dateFormatter.dateFromString(dataString)  //my expiringTime variable here always returns nil

Any code here after I do with expiringTime doesn't work because it always returns nil. Please help! Here is where expirationField.text comes from:

// Expiration Field

@IBAction func expirationFieldEditing(sender: UITextField) {
    let datePickerView:UIDatePicker = UIDatePicker()
    datePickerView.datePickerMode = UIDatePickerMode.Date
    sender.inputView = datePickerView
    datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}

func datePickerValueChanged(sender:UIDatePicker) {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
    expirationField.text = dateFormatter.stringFromDate(sender.date)
}

Thanks in advance!

您需要在dateFormatter上设置dateStyle属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM