新手在这里尝试修改苹果提供的“日期单元”示例代码以用于学习目的,并且在格式化日期方面遇到了真正的麻烦。我有一个 tableView,在第 1 行 (datePickerModeDateAndTime)、第 2 行 (pickerModeDate)、第 3 行 (pickerModeTime) 中有三个单独的 datePicker。现在,我正在努力从记录的第一个选择器(dateAndTime)中获取值,以便以后可以访问它。我以“2013 年 9 月 20 日,下午 12:12”的形式在 tableView 单元格的详细信息中显示了所选日期。我正在尝试获取详细信息的值并将“NSDate 日期”和所选时间之间的差异写入 DD:HH:MM:SS 剩余的应用程序文档目录中,以便我可以设置一个计时器另一个视图开始倒计时到选定的日期/时间并在 UILabel 中显示计时器计数。I have the log writing the date as '2013-09-20 18:12:33 +0000' when the picker is initially loaded to the screen but after the components change the log reads '0:00:00:-10'. 所以我已经部分完成了我想要的,但没有成功地从中获得正确的日期。谢谢!
if(self.datePickerIndexPath.row == 1){
targetedDatePicker.datePickerMode = UIDatePickerModeDateAndTime;
self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[self.dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSDate *selected = [NSDate dateWithTimeIntervalSince1970:[self.pickerView.date timeIntervalSince1970] - 1];
self.deadlineCounter = [self.formatter stringFromDate:selected];
NSLog(@"selected is: %@", selected);
NSDate *todaysDate = [NSDate date];
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];
self.DeadlineCounter = [NSString stringWithFormat:@"%ld:%02ld:%02ld:%02ld",
(long)days,
(long)hours,
(long)minutes,
(long)seconds];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:@"%@/deadline.txt", documentsDirectory];
NSInteger success = [NSKeyedArchiver archiveRootObject:selected toFile:deadline];
NSLog(@"success is: %d",success);
NSLog(@"deadline.txt was written successfully with these contents %@,", self.deadlineCounter);
targetedDatePicker.minimumDate = [NSDate date];
targetedDatePicker.maximumDate = [todaysDate dateByAddingTimeInterval:604800];
}
基本上,如果用户从日期选择器中选择“2013 年 9 月 25 日,下午 2:25”,我想编写字符串以便可以创建倒数计时器,显示在另一个视图中,并设置为关闭并选择日期和时间。(我已经得到要在正确的控制器上写入和读取的日期,并且 timerLabel 以“0:00:00:00”的形式显示日期,但这是错误的数字)