我想从日期选择器中获取日,月,年的单独字符串值。并将这三个值分配给3个变量。我已经做到了这一点:
@IBAction func doneClicked(sender: UIButton) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = GlobalConfiguration.getDatePickerFormat()
let formattedDate = dateFormatter.stringFromDate(self.datePicker.date)
self.delegate?.datePickerDidSelect(formattedDate)
}
这是我的几个代码,我可以将日期文本设置为按钮标题的字符串。现在我分别想要日,月和年。我怎么能这样做.. ??
答案 0 :(得分:3)
你有两种方法可以做到这一点,取决于你是否想看到当月的数字或他的名字:
使用Calendar:
let calendar = Calendar.current
let components = calendar.dateComponents([.day,.month,.year], from: self.datePicker.date))
if let day = components.day, let month = components.month, let year = components.year {
let dayString = String(day)
let monthString = String(month)
let yearString = String(year)
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy"
let year: String = dateFormatter.string(from: self.datePicker.date))
dateFormatter.dateFormat = "MM"
let month: String = dateFormatter.string(from: self.datePicker.date))
dateFormatter.dateFormat = "dd"
let day: String = dateFormatter.string(from: self.datePicker.date))
使用DateFormatter,您可以选择更多格式,因为您管理输出格式
答案 1 :(得分:1)
斯威夫特3:
if let date = self.datePicker.date {
let components = NSCalendar.current.dateComponents([.day,.month,.year],from:date)
if let day = components.day, let month = components.month, let year = components.year {
let dayString = "\(day)"
let monthString = "\(month)"
let yearString = "\(year)"
}
}
答案 2 :(得分:1)
您可以使用NSDateComponents
。
let dateComponents = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: self.datePicker.date)
let year = String(dateComponents.year)
let month = String(dateComponents.month)
let day = String(dateComponents.day)