1

我正在尝试从两个不同的日期构建一个日期。当我将两个日期分解成各自的组成部分并将它们重新组合成新的日期时……除了时间之外,一切似乎都是正确的。我确定它与时区或 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);

打印 modifiedCorrectedDate 的日志结果显示我设置的所有内容都正确,但小时数除外。这必须是一个简单的修复..我只是没有看到它。先感谢您!

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,显示的日期是 6/4/12 01:13:36,这是正确的时间,以 UTC 表示(注意末尾的 +0000)。

于 2012-06-04T01:19:12.710 回答