如何从今天起一个月后设置日期选择器最短日期

时间:2016-08-05 04:59:58

标签: ios iphone swift datepicker

我在xcode7.3.1中使用swift。我想设置我的日期选择器最短日期必须是从今天起一个月。我使用以下代码。我认为它不正确的方式。请你帮我解决这个问题。

  let calendar = NSCalendar.currentCalendar()
  let oneMonthBack = calendar.dateByAddingUnit(.Day, value: -30, toDate: NSDate(), options: [])
  datePicker.minimumDate = oneMonthBack

2 个答案:

答案 0 :(得分:2)

尝试此功能

func previousMonth(sender : AnyObject) {
        let currentCalendar = NSCalendar.currentCalendar()
        let dateComponents = NSDateComponents()
        dateComponents.month = -1
        let oneMonthBack = currentCalendar.dateByAddingComponents(dateComponents, toDate: NSDate(), options: [])!
    }

答案 1 :(得分:2)

喜欢

    let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
     calendar.timeZone = NSTimeZone(name: "UTC")!
     let components: NSDateComponents = NSDateComponents()
    components.calendar = calendar
     components.month = -1 // this is for month
    let minDate: NSDate = calendar.dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
     print("minDate: \(minDate)")
     datePicker.minimumDate = minDate

你得到了

的输出

enter image description here