问题
Need a UIDatePicker with specific maximum and minimum dates and times. Currently NSDatePicker.minimumDate and .maximumDate appear to only consider the date. What's the proper way to handle this?
回答1:
NSDates contain both the date and the time. From the docs:
NSDate objects represent a single point in time.
The example below has the current date and time as the minimum value and the time an hour from now as the maximum value (to test it just drop it into the viewDidLoad of any UIViewController):
// Time right now
NSDate *minDate = [NSDate new];
// One hour from now
NSDate *maxDate = [[NSDate alloc] initWithTimeIntervalSinceNow:60*60];
UIDatePicker *picker = [UIDatePicker new];
[picker setDatePickerMode:UIDatePickerModeDateAndTime];
[picker setMinimumDate:minDate];
[picker setMaximumDate:maxDate];
[[self view] addSubview:picker];
[super viewDidLoad];
You can read more about NSDate on the Dev Center.
回答2:
NSDateFormatter *FormatDate = [[[NSDateFormatter alloc] init] autorelease];
[FormatDate setDateFormat:@"MMMM d y"];
NSString *date1=[FormatDate stringFromDate:[theDatePicker date]];
NSString *today=[FormatDate stringFromDate:[NSDate date]];
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
NSString *tommorow=[FormatDate stringFromDate:tomorrow];
[pickerViewPopup dismissWithClickedButtonIndex:0 animated:YES];
if ([date1 isEqualToString:today]||[date1 isEqualToString:tommorow] ) {
NSDateFormatter *FormatDate = [[[NSDateFormatter alloc] init] autorelease];
[FormatDate setDateFormat:@"MMM dd,yyyy"];
currentdate.text = [FormatDate stringFromDate:[theDatePicker date]];
来源:https://stackoverflow.com/questions/2441282/can-uidatepickers-minimumdate-and-maximumdate-include-time