简体   繁体   English

UIDatePicker,根据日期名称和今天的日期设置最大和最小日期

[英]UIDatePicker, setting maximum and minimum dates based on day names and todays date

I have a UIDatePicker, and I wish to set the minimum and maximum date range to be between Thursday to Wednesday of the current week, how would I set that up? 我有一个UIDatePicker,我希望将最小和最大日期范围设置为当前周的星期四至星期三之间,如何设置? picker date is the date picker and datepicker text field is text field 选择器日期是日期选择器,日期选择器文本字段是文本字段

pickerDate.datePickerMode = UIDatePickerMode.Date
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
datePickerTextField.text = dateFormatter.stringFromDate(pickerDate.date)

I would try the following: 我会尝试以下方法:

  • Create an instance of NSCalendar 创建NSCalendar的实例
  • Create the date components (including NSCalendarUnit.WeekOfYear from the current date using the calendar 使用日历从当前日期创建日期组件(包括NSCalendarUnit.WeekOfYear
  • Create date components with the desired values for NSCalendarUnit.Weekday 使用NSCalendarUnit.Weekday创建具有所需值的日期组件
  • Use calendar to calculate the dates from the date components 使用日历从日期组件中计算日期

I think you want something like this. 我想你想要这样的东西。

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *currentDate = [NSDate date];

NSDateComponents *comps = [[NSDateComponents alloc] init];

[comps setDay: -7];
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

[datePicker setMaximumDate:currentDate];
[datePicker setMinimumDate:minDate];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM