遇到了一个非常令人沮丧的问题,似乎没有任何意义。我正在尝试获取两个日期之间的年数。这是我的代码。
// Initialize variable to store calendar
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Break out date to year component
NSDateComponents *Components = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
// Debugging code
NSLog(@"Debug start date = %@",startDate);
NSLog(@"Debug end date = %@", endDate);
NSLog(@"Debug year = %d",[Components year]);
NSLog(@"Debug month = %d",[Components month]);
NSLog(@"Debug day = %d", [Components day]);
NSLog(@"Debug hours = %d",[Components hour]);
NSLog(@"Debug minutes = %d", [Components minute]);
NSLog(@"Debug seconds = %d", [Components second]);
[gregorian release];
// Check which component to extract and return value accordingly
// Defaults to month for now
if ([datecomponent isEqualToString:@"year"]) {
return [Components year];
}
else {
return [Components month];
}
开始和结束日期由其他地方的 UIDatePickers 设置。他们将默认相隔 10 年。一旦我回到控制结束日期的 UIDatePicker 并将其移至一年前。问题将开始出现。这是我将结束日期移回原始日期后将看到的 NSLog 示例。我应该在其他地方看到 10 年和 0,但我错过了 1 秒的时间。
Debug start date = 2011-08-15 15:55:07 +0000
Debug end date = 2021-08-15 15:55:07 +0000
Debug year = 9
Debug month = 11
Debug day = 30
Debug hours = 23
Debug minutes = 59
Debug seconds = 59
在我看来,开始和结束日期在它们之间的 10 年中保存的时间相同,但由于某种原因,我错过了 1 秒的时间。有谁知道为什么?
提前致谢!
添加
这是我初始化和存储 2 个日期的方式。
开始日期在 viewWillAppear 方法中。
- (void)viewWillAppear:(BOOL)animated {
if ([managedObject valueForKeyPath:self.keypath] != nil)
[self.datePicker setDate:[managedObject
valueForKeyPath:keypath] animated:YES];
else
[self.datePicker setDate:[NSDate date] animated:YES];
[self.tableView reloadData];
[super viewWillAppear:animated];
}
我的结束日期也使用了相同的类,但是我还在我的 NSManagedObject 的自定义子类中添加了以下代码:-
- (void)awakeFromInsert {
[super awakeFromInsert];
// Set default date of registration to be today's date
self.startdate = [NSDate date];
NSDate *today = [[NSDate alloc] init]; // I also tried to equate this to self.startdate but there is no difference
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:10];
self.enddate = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
}
这会引起任何问题吗?如果是,为什么调试会显示开始和结束日期,包括它们的时间完全相同?