从UIDatePicker获取日期(没时间)

时间:2015-04-07 22:04:23

标签: swift datepicker

我想从UIDatePicker获取日期:

myDatePicker.datePickerMode = UIDatePicker.Mode.date
var selectedDate=myDatePicker.date
println(selectedDate)

然而,这打印的日期多于日期(打印2015-04-09 21:45:13 +0000)。如何获得日期部分(没有时间)?我还将日期选择器Mode属性设置为Date。

6 个答案:

答案 0 :(得分:23)

根据Apple的文档datePicker.mode应为date,因此您可以DateFormatter使用

Swift 4

datePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy"
let selectedDate = dateFormatter.string(from: datePicker.date)
print(selectedDate)

答案 1 :(得分:7)

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy"
let dateString = dateFormatter.stringFromDate(myDatePicker.date)

您可以打印dateString,将其分配给标签,无论如何。格式为

  

15年4月9日

答案 2 :(得分:5)

Swift 3/4,这将打印2017年3月8日类型的字符串

   datePicker.datePickerMode = .date
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM dd, yyyy"
    let selectedDate = dateFormatter.string(from: datePicker.date)
    print(selectedDate)

答案 3 :(得分:3)

我只是想在遇到类似的问题后在这里添加我的位。我会按照阴影回答字符串显示日期。当您使用UIDatePicker时,不是从XCode 7和swift 2开始设置以下内容以仅查看Picker中的日期:

@IBOutlet weak var datePicker: UIDatePicker!
datePicker.datePickerMode = .Date

答案 4 :(得分:3)

Swift 4.0版本代码在这里

@IBAction func saveDateAction(_ sender: Any) {

        myDatePicker.datePickerMode = UIDatePicker.Mode.date
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd MMM yyyy"
        let selectedDate = dateFormatter.string(from: myDatePicker.date)
        print("selectedDate",selectedDate)    
    }

答案 5 :(得分:0)

日期选择器日期:

let date = datePicker.date
let dateConverted = Date.init(year: date.GetYear(), month: date.GetMonth(), day: date.GetDay())
//dateConverted result = 2019-02-27 00:00:00 +0000
let predicate = NSPredicate(format: "booking_date == %@", dateConverted as CVarArg)

使用此扩展程序:

extension Date {

init(year: Int, month: Int, day: Int) {
    var dc = DateComponents()
    dc.year = year
    dc.month = month
    dc.day = day

    var calendar = Calendar(identifier: .gregorian)
    calendar.timeZone = TimeZone(secondsFromGMT: 0)!
    if let date = calendar.date(from: dc) {
        self.init(timeInterval: 0, since: date)
    } else {
        fatalError("Date component values were invalid.")
    }
}

func GetYear() -> Int {
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
    let components = calendar.components([.day , .month , .year], from: self)
    return components.year!
}

func GetMonth() -> Int {
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
    let components = calendar.components([.day , .month , .year], from: self)
    return components.month!
}

func GetDay() -> Int {
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
    let components = calendar.components([.day , .month , .year], from: self)
    return components.day!
}
}