我正在尝试在表单中的标签中显示与UIDatePicker
输入时间和真实世界时间的时差。我显示了正确的信息,但我很难让相同的数据显示在我的标签中。截至目前,我的 UILabel 中没有显示任何内容,但正确的数据在 NSLog 中。当我改变IBOutlet
dd:hh:mm:ss
NSLog
[self.formatter stringFromDate:timeDif];
至
[self.formatter stringFromDate:selected];
显示当前 DatePicker 选择时间(这不是我想要的),但 NSLog 仍然正确显示时差。我知道我的格式化顺序有问题,但我无法看到哪里出错了。
- (IBAction)displayDate:(id)sender {
NSDate *timeDif = [self.formatter dateFromString:self.string];
NSDate *todaysDate = [NSDate date];
NSDate *selected = [picker date];
self.formatter = [NSDateFormatter new];
[self.formatter setDateFormat:@"dd:hh:mm:ss"];
[picker setDate:selected animated:YES];
self.label.text = [self.formatter stringFromDate:timeDif];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComparisonComponents = [gregorian components:unitFlags
fromDate:todaysDate
toDate:selected
options:NSWrapCalendarComponents];
NSInteger days = [dateComparisonComponents day];
NSInteger hours = [dateComparisonComponents hour];
NSInteger minutes = [dateComparisonComponents minute];
NSInteger seconds = [dateComparisonComponents second];
dateComponents.day = days;
dateComponents.hour = hours;
dateComponents.minute = minutes;
dateComponents.second = seconds;
self.string = [NSString stringWithFormat:@"%1d:%1d:%1d:%1d",
dateComparisonComponents.day,
dateComparisonComponents.hour,
dateComparisonComponents.minute,
dateComparisonComponents.second];
NSLog(@"%1d:%1d:%1d:%1d",
dateComparisonComponents.day,
dateComparisonComponents.hour,
dateComparisonComponents.minute,
dateComparisonComponents.second);
}