Swift: How to get string values of days, months and year from a date picker?

[亡魂溺海] 提交于 2019-12-08 13:54:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!