Swift:如何从日期选择器获取天,月和年的字符串值? [英] Swift: How to get string values of days, months and year from a date picker?

查看:393
本文介绍了Swift:如何从日期选择器获取天,月和年的字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从日期选择器中获取天,月,年的单独字符串值。并将这三个值分配给3个变量。我已经做到了这一点:

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..??

推荐答案

您有2种方法,具体取决于您是否要查看数字本月的月份或他的名字:

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

使用日历

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)
}

使用 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))

使用 DateFormatter ,您可以选择更多格式,因为您可以管理输出格式

With DateFormatter you have more choice of formatting because your manage the output format

这篇关于Swift:如何从日期选择器获取天,月和年的字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆