1

2つの異なる日付から日付を作成しようとしています。両方の日付をそれぞれのコンポーネントに分解し、新しい日付に再組み立てすると、時間以外はすべて正しいようです。タイムゾーンやNSGregorianCalendarに関係する単純なことだと思いますが、私はiOSとNSCalendarのプログラミングに不慣れです。誰かが私が犯した単純な間違いを捕まえることを望んでいます。

//grab today's date so we can brek it down into components
NSDate *todayDate = [NSDate date];

NSLog(@"Todays Date: %@", todayDate);

NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];

//break down the stored date into components
NSDateComponents *theTime = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:storedIncorrectDate];

NSLog(@"Incorrect Calendar Components %@", theTime);

NSDateComponents *todayCalendarComponents = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:todayDate];

NSInteger currentYear = [todayCalendarComponents year];

NSLog(@"The Year: %i", currentYear);

NSInteger currentMonth = [todayCalendarComponents month];

NSLog(@"The Month: %i", currentMonth);

NSInteger currentDay = [todayCalendarComponents day];

NSLog(@"The Day: %i", currentDay);


NSLog(@"Today's Calendar Components %@", todayCalendarComponents);


NSInteger theHours = [theTime hour];

NSLog(@"Hours: %i", theHours);

NSInteger theMinutes = [theTime minute];

NSLog(@"Minutes: %i", theMinutes);


NSInteger theSeconds = [theTime second];

NSLog(@"Seconds: %i", theSeconds);

//build my new date and store it before we play the affirmation.
NSDateComponents *components = [[NSDateComponents alloc] init];


[components setHour:theHours];
[components setMinute:theMinutes]; 
[components setSecond:theSeconds]; 
[components setYear:currentYear];
[components setMonth:currentMonth];
[components setDay:currentDay];
[components setTimeZone:[NSTimeZone localTimeZone]];


NSLog(@"The Components: %@", components);

NSCalendar *updatedCal = [[NSCalendar alloc]
                          initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *revisedCorrectedDate = [updatedCal dateFromComponents:components]; 

NSLog(@"The Hours: %i", theHours);

NSLog(@"The New and Corrected Date: %@", revisedCorrectedDate);

改訂されたCorrectedDateを印刷するログの結果は、時間を除いて私が設定したすべての正しいことを示しています。これは簡単な修正である必要があります。私はそれが表示されません。前もって感謝します!

4

1 に答える 1

0

間違っていますか?このコードを実行すると、次のようになります。

2012-06-03 18:13:36.130無題[39805:707]新規および修正日:2012-06-04 01:13:36 +0000

現在、ここでは6/3/12 18:13:36であり、表示される日付はUTCでの正しい時刻である6/4/12 01:13:36です(最後に+0000があることに注意してください)。

于 2012-06-04T01:19:12.710 に答える