UIDatePicker中的最小和最大日期

时间:2022-04-17 16:04:27

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.

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

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

假设当前年份是2018年,那么我想要最小日期2000和最大日期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..

但是我不能把这个整数变成我的日期格式..

11 个解决方案

#1


58  

Try this:

尝试这个:

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;

It may be easily translated to Swift:

它可以很容易地翻译成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

#2


14  

In Swift 2.1:

在Swift 2.1中:

    let currentDate: NSDate = NSDate()

    let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    // let calendar: NSCalendar = NSCalendar.currentCalendar()
    calendar.timeZone = NSTimeZone(name: "UTC")!

    let components: NSDateComponents = NSDateComponents()
    components.calendar = calendar

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

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

    self.dateOfBirthUIDatePicker.minimumDate = minDate
    self.dateOfBirthUIDatePicker.maximumDate = maxDate

    print("minDate: \(minDate)")
    print("maxDate: \(maxDate)")

#3


12  

This is how it would look like in 2017 (Swift 3)

这就是2017年的样子(Swift 3)

    var components = DateComponents()
    components.year = -100
    let minDate = Calendar.current.date(byAdding: components, to: Date())

    components.year = -18
    let maxDate = Calendar.current.date(byAdding: components, to: Date())

    datePicker.minimumDate = minDate
    datePicker.maximumDate = maxDate

#4


10  

Swift 4.1

extension UIDatePicker {
    func set18YearValidation() {
        let currentDate: Date = Date()
        var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
        calendar.timeZone = TimeZone(identifier: "UTC")!
        var components: DateComponents = DateComponents()
        components.calendar = calendar
        components.year = -18
        let maxDate: Date = calendar.date(byAdding: components, to: currentDate)!
        components.year = -150
        let minDate: Date = calendar.date(byAdding: components, to: currentDate)!
        self.minimumDate = minDate
        self.maximumDate = maxDate
    } }

#5


6  

Swift 3.0

Swift 3.0

 let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
    let currentDate: Date = Date()
    let components: NSDateComponents = NSDateComponents()

    components.year = -150
    let minDate: Date = gregorian.date(byAdding: components as DateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))!

    components.year = -16
    let maxDate: Date = gregorian.date(byAdding: components as DateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))!

    self.datepicker.minimumDate = minDate
    self.datepicker.maximumDate = maxDate

#6


2  

In Objective C, NSDateComponents *comps = [[NSDateComponents alloc] init];

在Objective C中,NSDateComponents * comps = [[NSDateComponents alloc] init];

NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];

NSInteger year = components.year;
NSInteger month = components.month;
NSInteger day = components.day;
NSInteger minimumYear = year - 1900;//Given some year here for example
NSInteger minimumMonth = month - 1;
NSInteger minimumDay = day - 1;
[comps setYear:-minimumYear];
[comps setMonth:-minimumMonth];
[comps setDay:-minimumDay];
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

[datePicker setMinimumDate:minDate];
[datePicker setMaximumDate:[NSDate date]];

The minimum date would be January 01 1900. I hope it works for you all.. :)

最短的日期是1900年1月1日。我希望它对你们都有用.. :)

In Swift 2.0 or later

在Swift 2.0或更高版本中

    let calendar = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian);

    let todayDate = NSDate()

    let components = calendar?.components([NSCalendarUnit.Year,NSCalendarUnit.Month,NSCalendarUnit.Day], fromDate: todayDate)
    let minimumYear = (components?.year)! - 1900
    let minimumMonth = (components?.month)! - 1
    let minimumDay = (components?.day)! - 1

    let comps = NSDateComponents();
    comps.year = -minimumYear
    comps.month = -minimumMonth
    comps.day = -minimumDay

    let minDate = calendar?.dateByAddingComponents(comps, toDate: todayDate, options: NSCalendarOptions.init(rawValue: 0))

    datePicker.minimumDate = minDate
    datePicker.maximumDate = datePicker.date

#7


2  

**Minimum and maximum date in UIDatePicker: #Swift

** UIDatePicker中的最短和最长日期:#Swift

**if you want to select the min and max date between two date value use below simple code: **

**如果您想在简单代码下面选择两个日期值之间的最小和最大日期:**

for Example : Min Date : 01-04-2017 and Max Date : 31-03-2018

例如:最小日期:01-04-2017和最大日期:31-03-2018

let calendar = Calendar.current
var minDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
minDateComponent.day = 01
minDateComponent.month = 04
minDateComponent.year = 2017

let minDate = calendar.date(from: minDateComponent)
print(" min date : \(String(describing: minDate))")

var maxDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
maxDateComponent.day = 0
maxDateComponent.month = 03 + 1
maxDateComponent.year = 2018

let maxDate = calendar.date(from: maxDateComponent)
print("max date : \(String(describing: maxDate))")

picker.minimumDate = minDate! as Date
picker.maximumDate =  maxDate! as Date

#8


1  

Swift 4.1

Swift 4.1

I have created my extension for all type of limit based on Calendar.Component

我已经基于Calendar.Component为所有类型的限制创建了我的扩展

extension UIDatePicker {

    func setLimit(forCalendarComponent component:Calendar.Component, minimumUnit min: Int, maximumUnit max: Int) {

        let currentDate: Date = Date()
        var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)

        guard let timeZone = TimeZone(identifier: "UTC") else { return }
        calendar.timeZone = timeZone

        var components: DateComponents = DateComponents()
        components.calendar = calendar

        components.setValue(-min, for: component)
        if let maxDate: Date = calendar.date(byAdding: components, to: currentDate) {
            self.maximumDate = maxDate
        }

        components.setValue(-max, for: component)
        if let minDate: Date = calendar.date(byAdding: components, to: currentDate) {
            self.minimumDate = minDate
        }
    }

}

We can use this as following:

我们可以使用如下:

self.datePicker.setLimit(forCalendarComponent: .year, minimumUnit: 13, maximumUnit: 100)

#9


0  

Another case :

另一个案例:

Suppose I want to show Date of birth as a Date picker, Dob is within the range of 1/1/1980 to  1/1/2000.

假设我想将出生日期显示为日期选择器,Dob在1/1/1980到1/1/2000的范围内。

@IBOutlet var datePicker: UIDatePicker!

override func viewDidLoad() {
        super.viewDidLoad()        
        datePicker.datePickerMode = UIDatePickerMode.date       


        // 01/01/1980 to 01/01/2000

        let calendar = Calendar.current
        var minDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
        minDateComponent.day = 01
        minDateComponent.month = 01
        minDateComponent.year = 1980

        let minDate = calendar.date(from: minDateComponent)
        print(" min date : \(minDate)")

        var maxDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
       maxDateComponent.day = 01
        maxDateComponent.month = 01
        maxDateComponent.year = 2000

        let maxDate = calendar.date(from: maxDateComponent)
        print("max date : \(maxDate)")

        self.datePicker.minimumDate = minDate! as Date
        self.datePicker.maximumDate =  maxDate! as Date

}

#10


0  

Swift 4.0

Swift 4.0

extension UIDatePicker { func set18YearValidation() { let currentDate: Date = Date() var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.timeZone = TimeZone(identifier: "UTC")! var components: DateComponents = DateComponents() components.calendar = calendar components.year = -18 let maxDate: Date = calendar.date(byAdding: components, to: currentDate)! components.year = -150 let minDate: Date = calendar.date(byAdding: components, to: currentDate)! self.minimumDate = minDate self.maximumDate = maxDate } }

extension UIDatePicker {func set18YearValidation(){let currentDate:Date = Date()var calendar:Calendar = Calendar(identifier:Calendar.Identifier.gregorian)calendar.timeZone = TimeZone(identifier:“UTC”)! var components:DateComponents = DateComponents()components.calendar = calendar components.year = -18 let maxDate:Date = calendar.date(byAdding:components,to:currentDate)! components.year = -150 let minDate:Date = calendar.date(byAdding:components,to:currentDate)! self.minimumDate = minDate self.maximumDate = maxDate}}

#11


0  

Look at this for Swift version. User negative value (-) to subtract and positive value to add date component.

看看这个Swift版本。用户负值( - )减去和正值添加日期组件。

1. Set minimum date

1.设置最短日期

yourDatePicker.minimumDate = Calendar.current.date(byAdding: .year, value: -1, to: Date())

yourDatePicker.minimumDate = Calendar.current.date(byAdding:.year,value:-1,to:Date())

2. Set maximum date

2.设置最大日期

yourDatePicker.maximumDate = Calendar.current.date(byAdding: .year, value: 1, to: Date())

yourDatePicker.maximumDate = Calendar.current.date(byAdding:。year,value:1,to:Date())

#1


58  

Try this:

尝试这个:

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;

It may be easily translated to Swift:

它可以很容易地翻译成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

#2


14  

In Swift 2.1:

在Swift 2.1中:

    let currentDate: NSDate = NSDate()

    let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    // let calendar: NSCalendar = NSCalendar.currentCalendar()
    calendar.timeZone = NSTimeZone(name: "UTC")!

    let components: NSDateComponents = NSDateComponents()
    components.calendar = calendar

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

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

    self.dateOfBirthUIDatePicker.minimumDate = minDate
    self.dateOfBirthUIDatePicker.maximumDate = maxDate

    print("minDate: \(minDate)")
    print("maxDate: \(maxDate)")

#3


12  

This is how it would look like in 2017 (Swift 3)

这就是2017年的样子(Swift 3)

    var components = DateComponents()
    components.year = -100
    let minDate = Calendar.current.date(byAdding: components, to: Date())

    components.year = -18
    let maxDate = Calendar.current.date(byAdding: components, to: Date())

    datePicker.minimumDate = minDate
    datePicker.maximumDate = maxDate

#4


10  

Swift 4.1

extension UIDatePicker {
    func set18YearValidation() {
        let currentDate: Date = Date()
        var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
        calendar.timeZone = TimeZone(identifier: "UTC")!
        var components: DateComponents = DateComponents()
        components.calendar = calendar
        components.year = -18
        let maxDate: Date = calendar.date(byAdding: components, to: currentDate)!
        components.year = -150
        let minDate: Date = calendar.date(byAdding: components, to: currentDate)!
        self.minimumDate = minDate
        self.maximumDate = maxDate
    } }

#5


6  

Swift 3.0

Swift 3.0

 let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
    let currentDate: Date = Date()
    let components: NSDateComponents = NSDateComponents()

    components.year = -150
    let minDate: Date = gregorian.date(byAdding: components as DateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))!

    components.year = -16
    let maxDate: Date = gregorian.date(byAdding: components as DateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))!

    self.datepicker.minimumDate = minDate
    self.datepicker.maximumDate = maxDate

#6


2  

In Objective C, NSDateComponents *comps = [[NSDateComponents alloc] init];

在Objective C中,NSDateComponents * comps = [[NSDateComponents alloc] init];

NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];

NSInteger year = components.year;
NSInteger month = components.month;
NSInteger day = components.day;
NSInteger minimumYear = year - 1900;//Given some year here for example
NSInteger minimumMonth = month - 1;
NSInteger minimumDay = day - 1;
[comps setYear:-minimumYear];
[comps setMonth:-minimumMonth];
[comps setDay:-minimumDay];
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

[datePicker setMinimumDate:minDate];
[datePicker setMaximumDate:[NSDate date]];

The minimum date would be January 01 1900. I hope it works for you all.. :)

最短的日期是1900年1月1日。我希望它对你们都有用.. :)

In Swift 2.0 or later

在Swift 2.0或更高版本中

    let calendar = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian);

    let todayDate = NSDate()

    let components = calendar?.components([NSCalendarUnit.Year,NSCalendarUnit.Month,NSCalendarUnit.Day], fromDate: todayDate)
    let minimumYear = (components?.year)! - 1900
    let minimumMonth = (components?.month)! - 1
    let minimumDay = (components?.day)! - 1

    let comps = NSDateComponents();
    comps.year = -minimumYear
    comps.month = -minimumMonth
    comps.day = -minimumDay

    let minDate = calendar?.dateByAddingComponents(comps, toDate: todayDate, options: NSCalendarOptions.init(rawValue: 0))

    datePicker.minimumDate = minDate
    datePicker.maximumDate = datePicker.date

#7


2  

**Minimum and maximum date in UIDatePicker: #Swift

** UIDatePicker中的最短和最长日期:#Swift

**if you want to select the min and max date between two date value use below simple code: **

**如果您想在简单代码下面选择两个日期值之间的最小和最大日期:**

for Example : Min Date : 01-04-2017 and Max Date : 31-03-2018

例如:最小日期:01-04-2017和最大日期:31-03-2018

let calendar = Calendar.current
var minDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
minDateComponent.day = 01
minDateComponent.month = 04
minDateComponent.year = 2017

let minDate = calendar.date(from: minDateComponent)
print(" min date : \(String(describing: minDate))")

var maxDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
maxDateComponent.day = 0
maxDateComponent.month = 03 + 1
maxDateComponent.year = 2018

let maxDate = calendar.date(from: maxDateComponent)
print("max date : \(String(describing: maxDate))")

picker.minimumDate = minDate! as Date
picker.maximumDate =  maxDate! as Date

#8


1  

Swift 4.1

Swift 4.1

I have created my extension for all type of limit based on Calendar.Component

我已经基于Calendar.Component为所有类型的限制创建了我的扩展

extension UIDatePicker {

    func setLimit(forCalendarComponent component:Calendar.Component, minimumUnit min: Int, maximumUnit max: Int) {

        let currentDate: Date = Date()
        var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)

        guard let timeZone = TimeZone(identifier: "UTC") else { return }
        calendar.timeZone = timeZone

        var components: DateComponents = DateComponents()
        components.calendar = calendar

        components.setValue(-min, for: component)
        if let maxDate: Date = calendar.date(byAdding: components, to: currentDate) {
            self.maximumDate = maxDate
        }

        components.setValue(-max, for: component)
        if let minDate: Date = calendar.date(byAdding: components, to: currentDate) {
            self.minimumDate = minDate
        }
    }

}

We can use this as following:

我们可以使用如下:

self.datePicker.setLimit(forCalendarComponent: .year, minimumUnit: 13, maximumUnit: 100)

#9


0  

Another case :

另一个案例:

Suppose I want to show Date of birth as a Date picker, Dob is within the range of 1/1/1980 to  1/1/2000.

假设我想将出生日期显示为日期选择器,Dob在1/1/1980到1/1/2000的范围内。

@IBOutlet var datePicker: UIDatePicker!

override func viewDidLoad() {
        super.viewDidLoad()        
        datePicker.datePickerMode = UIDatePickerMode.date       


        // 01/01/1980 to 01/01/2000

        let calendar = Calendar.current
        var minDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
        minDateComponent.day = 01
        minDateComponent.month = 01
        minDateComponent.year = 1980

        let minDate = calendar.date(from: minDateComponent)
        print(" min date : \(minDate)")

        var maxDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
       maxDateComponent.day = 01
        maxDateComponent.month = 01
        maxDateComponent.year = 2000

        let maxDate = calendar.date(from: maxDateComponent)
        print("max date : \(maxDate)")

        self.datePicker.minimumDate = minDate! as Date
        self.datePicker.maximumDate =  maxDate! as Date

}

#10


0  

Swift 4.0

Swift 4.0

extension UIDatePicker { func set18YearValidation() { let currentDate: Date = Date() var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.timeZone = TimeZone(identifier: "UTC")! var components: DateComponents = DateComponents() components.calendar = calendar components.year = -18 let maxDate: Date = calendar.date(byAdding: components, to: currentDate)! components.year = -150 let minDate: Date = calendar.date(byAdding: components, to: currentDate)! self.minimumDate = minDate self.maximumDate = maxDate } }

extension UIDatePicker {func set18YearValidation(){let currentDate:Date = Date()var calendar:Calendar = Calendar(identifier:Calendar.Identifier.gregorian)calendar.timeZone = TimeZone(identifier:“UTC”)! var components:DateComponents = DateComponents()components.calendar = calendar components.year = -18 let maxDate:Date = calendar.date(byAdding:components,to:currentDate)! components.year = -150 let minDate:Date = calendar.date(byAdding:components,to:currentDate)! self.minimumDate = minDate self.maximumDate = maxDate}}

#11


0  

Look at this for Swift version. User negative value (-) to subtract and positive value to add date component.

看看这个Swift版本。用户负值( - )减去和正值添加日期组件。

1. Set minimum date

1.设置最短日期

yourDatePicker.minimumDate = Calendar.current.date(byAdding: .year, value: -1, to: Date())

yourDatePicker.minimumDate = Calendar.current.date(byAdding:.year,value:-1,to:Date())

2. Set maximum date

2.设置最大日期

yourDatePicker.maximumDate = Calendar.current.date(byAdding: .year, value: 1, to: Date())

yourDatePicker.maximumDate = Calendar.current.date(byAdding:。year,value:1,to:Date())