简体   繁体   中英

How to judge whether selected date has exceeded the range in UIDatePicker?

Now I have set the minimumDate and maximumDate of UIDatePicker like this

_timePicker.minimumDate = [[NSDate date] dateByAddingTimeInterval:60];
_timePicker.maximumDate = [[NSDate date] dateByAddingTimeInterval:86400*10];

and I have added a target

[_timePicker addTarget:self action:@selector(labelContentDidChange:) forControlEvents:UIControlEventValueChanged];

I want to show an alert when a user has selected date which is not in that range, but every time the labelContentDidChange is invoked, the date property has been changed automatically and I can't get what the user has selected before, for example, if I select time currently, the datePicker will scroll to time one minute later, and the date I get in labelContentDidChange is already one minute later.

Maybe compare date that user have picked to minimum and maximum dates?

// assume we have NSDate* pickedDate

NSDate *minimumDate = [[NSDate date] dateByAddingTimeInterval:60];
NSDate *maximumDate = [[NSDate date] dateByAddingTimeInterval:86400*10];

// if picked date is earlier than minimumDate, OR if it is later than maximumDate - show alert
if ([pickedDate compare:minimumDate] == NSOrderedAscending ||
    [pickedDate compare:maximumDate] == NSOrderedDescending) {
        // show your alert
    } else {
       // valid date was picked
    }

Though if you set these minimum and maximum as properties to your datePicker user would not be able to choose invalid dates, it would only makes sense for some other custom periods of times...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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