xcode Swift:如何从日期选择器中获取日期、月份和年份的字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44040875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: How to get string values of days, months and year from a date picker?
提问by Sam
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:
我想从日期选择器中获取日、月、年的单独字符串值。并将这三个值分配给一个 3 个变量。我已经做到了这一点:
@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..??
这是我的几个代码,我可以将日期文本设置为按钮标题的字符串。现在我想要分别天、月和年。我怎样才能做到这一点..??
回答by Julien Kode
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 DateFormatteryou have more choice of formatting because your manage the output format
使用DateFormatter,您有更多的格式选择,因为您管理输出格式
回答by Nirav D
You can use NSDateComponents
for that.
你可以用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)
回答by Yun CHEN
Swift 3:
斯威夫特 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)"
}
}