问题
I am using swift with xcode7.3.1 . I want to set my date picker minimum date must be one month back from today.I am using the following code.I think its not correct way.Could you please help me on this scenario.
let calendar = NSCalendar.currentCalendar()
let oneMonthBack = calendar.dateByAddingUnit(.Day, value: -30, toDate: NSDate(), options: [])
datePicker.minimumDate = oneMonthBack
回答1:
try this function
func previousMonth(sender : AnyObject) {
let currentCalendar = NSCalendar.currentCalendar()
let dateComponents = NSDateComponents()
dateComponents.month = -1
let oneMonthBack = currentCalendar.dateByAddingComponents(dateComponents, toDate: NSDate(), options: [])!
}
回答2:
do like
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
you get the output of
来源:https://stackoverflow.com/questions/38781435/how-to-set-date-picker-minimum-date-with-one-month-back-from-today