如何从NSDate获得1小时的未来时差

时间:2015-04-05 14:58:37

标签: ios objective-c nsdate nsdateformatter nsdatecomponents

我想为用户启用一项功能,仅在距离当前时间1小时后执行功能。我究竟应该在下面的代码中传递toDate参数以获得与当前时间1小时的未来时差?我不知道如何在NSDateFormatterNSDateComponents中设置未来时间。所以不能写我尝试过的东西。

- (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;
}

2 个答案:

答案 0 :(得分:3)

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

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

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

更新

正如@uchuugaka所述,您可以使用日历方法here找到该版本。

答案 1 :(得分: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视频几次。非常值得您的时间和您的用户'经验会更好。