(Swift)
Import UIKitclassViewcontroller:uiviewcontroller {var datepicker:uidatepicker!func datepickerdatechanged (datepicker:uidatepicker) {println ("Selected date = \ (datepicker.date)") } Overridefunc viewdidload () {super.viewdidload () DatePicker=uidatepicker () datepicker.center=view.center View.addsubview (datePicker) Datepicker.addtarget (Self, Action:"datepickerdatechanged:", forControlEvents:. valuechanged)/*set the minimum and the maximum dates that it can display*/Let oneyeartime:nstimeinterval=365* -* -* -Let todaydate=nsdate () let Oneyearfromtoday=Todaydate.datebyaddingtimeinterval (oneyeartime) let Twoyearsfromtoday= Todaydate.datebyaddingtimeinterval (2*oneyeartime) Datepicker.minimumdate=Oneyearfromtoday datepicker.maximumdate=Twoyearsfromtoday}}
(OBJECTIVE-C)
#import "ViewController.h"@interfaceViewcontroller () @property (nonatomic, strong) Uidatepicker*Mydatepicker;@end@implementationViewcontroller- (void) datepickerdatechanged: (Uidatepicker *) Paramdatepicker {if([Paramdatepicker IsEqual:self.myDatePicker]) {NSLog (@"Selected date =%@", paramdatepicker.date); }}- (void) viewdidload {[Super viewdidload]; Self.mydatepicker=[[Uidatepicker alloc] init]; Self.myDatePicker.center=Self.view.center; [Self.view AddSubview:self.myDatePicker]; [Self.mydatepicker addtarget:self Action: @selector (datepickerdatechanged:) forcontrolevents:uicontroleventva Luechanged]; Nstimeinterval Oneyeartime=365* -* -* -; NSDate*todaydate =[NSDate Date]; NSDate*oneyearfromtoday =[TodayDate Datebyaddingtimeinterval:oneyeartime]; NSDate*twoyearsfromtoday = [TodayDate datebyaddingtimeinterval:2*Oneyeartime]; Self.myDatePicker.minimumDate=Oneyearfromtoday; Self.myDatePicker.maximumDate=Twoyearsfromtoday;}@end
iOS Development Tips-use Uidatepicker to select dates and times