使用datepicker格式化日期

时间:2016-10-05 20:50:04

标签: swift date

我对Swift来说是全新的,所以如果我问明显的话,请耐心等待。 我有一个日期选择器和一个标签。在更改datepicker上的日期时,标签以yyyy-mm-dd hh-mm-ss格式显示日期/时间。我的代码是

@IBAction func DtPicker(_ sender: UIDatePicker)
{
    let strDate = String(describing: sender.date)
    lblShowShifts.text = strDate
}

工作正常

我的问题是我只想将日期显示为dd-mm-yyyy(然后计算从控制日期开始的天数) 我迷路看着dateformatter等,似乎绕着圈子尝试各种排列。任何人都可以帮忙 - 感谢期待

1 个答案:

答案 0 :(得分:1)

@IBAction func DatePickerAction(sender:AnyObject){

    let strDate = String(sender.date)
    lblShowShifts.text = strDate

    let calendar: NSCalendar = NSCalendar.currentCalendar()
    let currenttDate  = NSDate()
    let dateString = String(sender.date)

    //Default formatter for UIDatePicker -> "yyyy-MM-dd HH:mm:ssZ"
    //Fisrtly you need to give the formmater in which date is coming
      and then later change it according to your requirements
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"

    let secondDate = dateFormatter.dateFromString(dateString)

    let date1 = calendar.startOfDayForDate(currenttDate)
    let date2 = calendar.startOfDayForDate(secondDate!)

    //Find number of days between two dates
    let flags = NSCalendarUnit.Day
    let components = calendar.components(flags, fromDate: date1, toDate: date2, options: [])

    //Here you can do the calculations

    print("number of days between current date and today\(components.day)")


}