从组件构造日期后,NSDate小时数不正确

时间:2012-06-03 22:53:56

标签: xcode ios5 nsdate nscalendar

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

日志打印修改后的修正日期的结果显示除了小时之外我设置的所有内容。这必须是一个简单的修复..我只是没有看到它。提前谢谢!

1 个答案:

答案 0 :(得分: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)