2015-04-05 40 views
0

我希望为用户启用一项功能,以便在当前时间1小时后执行功能。我在下面的代码中通过toDate参数究竟是什么时间才能得到当前时间的1小时未来时间差?我不知道如何在NSDateFormatterNSDateComponents中设置未来的时间。所以不能写我所尝试过的。如何从NSDate获得1小时的未来时间差

- (NSInteger)timeDifference:(NSDate *)fromDate ToDate:(NSDate *)toDate 
{ 

    NSLog(@" FromDate: %@, ToDate: %@",fromDate,toDate); 

    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *differenceValue = [calendar components:NSHourCalendarUnit 
                fromDate:fromDate toDate:toDate options:0]; 
    NSLog(@"Calculated hour difference : %d",[differenceValue hour]); 
    NSInteger hourDifference = [differenceValue hour]; 

    NSLog(@" HourDifference: %d",hourDifference); 
    return hourDifference; 
} 

回答

3

如果你想创建一个小时后的特定日期的日期,你可以使用dateByAddingTimeInterval方法,如:

NSDate *date = [NSDate date]; 
NSDate *plusOneHour = [date dateByAddingTimeInterval:60.0f * 60.0f]; 

NSLog(@"%@, %@", date, plusOneHour); 

修订

由于@uchuugaka声明,你可以使用日历方法here找到版本。

+1

这是会导致错误的幼稚和不正确的方法。 – uchuugaka 2015-04-05 15:29:02

+0

@uchuugaka我从来没有听说过这种方法不正确,但你可能是对的。 – 2015-04-05 15:36:13

+0

它会工作很多时间,但NSDate是一个很薄的包装周围的时间间隔,并不知道日历和时区的人的一部分。从某种意义上说,这是正确的。但实际上它忽略了所有发生在这个立法的任意角落案件的疯狂事件。 – uchuugaka 2015-04-05 15:40:05

1

有关便捷方法,请参阅NSCalendar标题。同时观看2013年的WWDC视频日历计算主题。 这东西真的很慢,使它成为文档,只是增加了一个时间间隔很多次的错误。所有这些组件对于正确使用它们都很重要。你需要有一个日历和时区来增加语义上有意义的小时。

这是一个陷阱,当处理午夜,闰年和夏令时这是不同的地方。

具体来说,在这种情况下,我会从NSCalendar.h

/* 
    This API returns a new NSDate object representing the date calculated by adding an amount of a specific component to a given date. 
    The NSCalendarWrapComponents option specifies if the component should be incremented and wrap around to zero/one on overflow, and should not cause higher units to be incremented. 
*/ 
- (NSDate *)dateByAddingUnit:(NSCalendarUnit)unit value:(NSInteger)value toDate:(NSDate *)date options:(NSCalendarOptions)options NS_AVAILABLE(10_9, 8_0); 

推荐这种但是也有在头这就够了几种方法。请仔细观看WWDC视频几次。值得你花时间和你的用户体验会更好。