问题
i want to get the separate Strings values of day,Month,year from a date picker. and assign these three values to a 3 variables. I have done upto this:
@IBAction func doneClicked(sender: UIButton) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = GlobalConfiguration.getDatePickerFormat()
let formattedDate = dateFormatter.stringFromDate(self.datePicker.date)
self.delegate?.datePickerDidSelect(formattedDate)
}
this is my few codes and i can set the date text as a string to the button title.Now i want days,month and year separately. How can i do this..??
回答1:
You have 2 ways to do that, depends if you want to see the number of the current month or his name:
- Use Calendar
- Use DateFormatter
With 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)
}
With DateFormatter:
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))
With DateFormatter you have more choice of formatting because your manage the output format
回答2:
You can use NSDateComponents
for that.
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)
回答3:
Swift 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)"
}
}
来源:https://stackoverflow.com/questions/44040875/swift-how-to-get-string-values-of-days-months-and-year-from-a-date-picker