-1

鉴于我有一个NSDate *timeRightNow这是当前时间。

从这个时间开始,我如何找到下一个晚上 8:00?

因此,如果现在是晚上 8:01,我会抓住明天晚上 8:00

如果是晚上 7:59,我会抓住今天晚上 8:00。

所以它是下一个即将到来的 8:00。

谢谢!

4

3 回答 3

2

@Vignesh 有正确的想法,但你不能只是在日期上增加几秒钟来获得另一天。您需要添加“一天”,因为可能会有时间变化。这是他的代码的修订版本。

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:20];
NSDate *today8PM = [calendar dateFromComponents:components];

NSDate *next8PM;

if ([now compare:today8PM] == NSOrderedDescending) {
  NSDateComponents *oneDay = [NSDateComponents new];
  oneDay.day = 1;
  next8PM = [calendar dateByAddingComponents:oneDay toDate:today8PM  options:0]
}
else {
  next8PM = today8PM;
}
于 2013-10-28T14:54:37.627 回答
1

这段代码应该做你想做的,

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:20];
NSDate *today8PM = [calendar dateFromComponents:components];

if ([now compare:today8PM] == NSOrderedDescending)
{
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
dateToBeIncremented = [calendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];
    NSLog(@"%@",dateToBeIncremented );

}
else
{
    NSLog(@"%@", today8PM );

}
于 2013-10-28T14:19:51.800 回答
1

我会使用NSDate-Extensions

然后您可以执行以下操作:

#import "NSDate-Utilities.h"

NSDate *next8pm;
if ([timeRightNow timeIntervalSinceDate:[timeRightNow dateAtStartOfDay]] < 16*3600)
{
    next8pm = [[timeRightNow dateAtStartOfDay] dateByAddingHours:16];
}
else
{
    next8pm = [[[timeRightNow dateAtStartOfDay] dateByAddingDays:1] dateByAddingHours:16];
}
于 2013-10-28T14:16:53.193 回答