- (UIDatePicker *) datePicker {
if (!_datePicker) {
_datePicker = [[UIDatePickeralloc] init];
[_datePickersetLocale:[[NSLocalealloc]initWithLocaleIdentifier:@"zh_CN"]];
[_datePickeraddTarget:selfaction:@selector(datePickerValueChanged:)forControlEvents:UIControlEventValueChanged];
}
return_datePicker;
}
-(void)datePickerValueChanged:(id)sender{
UIDatePicker* control = (UIDatePicker*)sender;
NSDate* date = control.date;
_curDate = date;
}
//20年后
- (NSDate *)defaultDateLater {
NSDate * currentDate = [NSDatedate];
NSCalendar* calendar = [NSCalendarcurrentCalendar];
NSDateComponents* components = [calendarcomponents:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnitfromDate:currentDate];
components.year= components.year +20;
NSCalendar *myCal = [[NSCalendaralloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *retDate = [myCaldateFromComponents:components];
return retDate;
}
BDWalletDatePickerView* view = [[BDWalletDatePickerViewalloc] initWithFrame:self.view.bounds];
NSDate *curDate = [NSDatedate]; ;
[view.datePickersetDate:curDate];
view.curDate = curDate;
view.datePicker.timeZone = [NSTimeZonesystemTimeZone];
[view.datePickersetMinimumDate:curDate];
[view.datePickersetMaximumDate:[selfdefaultDateLater]];
[view.datePickersetDatePickerMode:UIDatePickerModeDate];
view.delegate =self;
[self.viewaddSubview:view];
- (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate
{
//设置源日期时区
NSTimeZone* sourceTimeZone = [NSTimeZonetimeZoneWithAbbreviation:@"UTC"];//或GMT
//设置转换后的目标日期时区
NSTimeZone* destinationTimeZone = [NSTimeZonelocalTimeZone];
//得到源日期与世界标准时间的偏移量
NSInteger sourceGMTOffset = [sourceTimeZonesecondsFromGMTForDate:anyDate];
//目标日期与本地时区的偏移量
NSInteger destinationGMTOffset = [destinationTimeZonesecondsFromGMTForDate:anyDate];
//得到时间偏移量的差值
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//转为现在时间
NSDate* destinationDateNow = [[NSDatealloc] initWithTimeInterval:intervalsinceDate:anyDate];
return destinationDateNow;
}
#pragma mark -BDWalletDatePickerViewDelegate
- (void)datePickerView:(BDWalletDatePickerView *)datePicker didUserSelected:(DatePickerViewUserAction)userAction selectDate:(NSDate *) selDate {
if (DatePickerViewUserActionConfirm == userAction){
if (selDate) {
NSDate *suitableDate = [selfgetNowDateFromatAnDate:selDate];
NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
self.photoViewModel.expireDateText = [dateFormatterstringFromDate:suitableDate];
}
}
}
//值得注意的是NSDate里面存储的时间都是标准的时间,也就是时间小时值为北京时区-8,可能会差一天,在这里使用的时候要保证都是标准时间也就是+00000,最后在得到结果后在通过getNowDateFromatAnDate方法获得准确时间。这里不用担心时间选择器显示的问题,因为view.datePicker.timeZone = [NSTimeZone systemTimeZone];可以保证时间的正确显示。