鉴于我的NSDate *timeRightNow
是当前时间。
从现在开始,我如何找到下一个晚上8点?
因此,如果现在是晚上8:01我会抓住明天晚上8点
如果是晚上7:59,我会抓住今天晚上8点。
所以这是下一个即将到来的8点。
谢谢!
答案 0 :(得分: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;
}
答案 1 :(得分: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];
}
答案 2 :(得分: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 );
}