意味がないように見える、本当にイライラする問題があります。2つの日付の間の年数を取得しようとしています。これが私のコードです。
// 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 に戻り、それを最大 1 年前に移動します。問題が発生し始めます。これは、終了日を元の日付に戻した後に表示される 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];
}
これは何か問題を引き起こしたでしょうか?はいの場合、デバッグで開始日と終了日が時間を含めてまったく同じに表示されるのはなぜですか?