UIDatePicker中的最小和最大日期 [英] Minimum and maximum date in UIDatePicker

查看:289
本文介绍了UIDatePicker中的最小和最大日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从日期选择器中获取最小和最大日期,但最小日期应为当前日期的 - 18,最大日期应为当前日期的 - 100。

I want to get the minimum and maximum date from a date picker, but minimum date should be "- 18" of the current date and the maximum date should be "- 100" of current date.

假设当前年份是2018年,那么我想要最短日期2000和最长日期1918.

Suppose current year is 2018 then I want minimum date 2000 and maximum date 1918.

到目前为止,我所做的是:

What I have done so far is :

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];

NSInteger year = [components year];

int mindt = year - 18;

int maxdt = year -100;

   // NSDate * MinDate = [components year] - 18;

   // NSDate * MaxDate =  [components year] - 100;

   // self.datePicker.minimumDate = MinDate;

   // self.datePicker.maximumDate = MaxDate;

但我无法将此整数变为我的日期格式..

but I cant get this integer to my date format..

推荐答案

试试这个:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:-18];
NSDate *minDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
[comps setYear:-150];
NSDate *maxDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
[comps release];

self.datePicker.minimumDate = minDate;
self.datePicker.maximumDate = maxDate;

可以很容易地翻译成Swift:

It may be easily translated to Swift:

let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!   
let currentDate: NSDate = NSDate() 
let components: NSDateComponents = NSDateComponents()

components.year = -18
let minDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

components.year = -150
let maxDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

self.datePicker.minimumDate = minDate
self.datePicker.maximumDate = maxDate

这篇关于UIDatePicker中的最小和最大日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆