如何为最近的未来比赛制定NSDate目标?

时间:2013-09-04 18:25:36

标签: iphone ios objective-c nsdate

这是我想要的一个例子。用户可能会在我的应用程序中设置警报1分钟,以便他们可以测试它。时间可能是19:23,所以他们会将闹钟设置为19:24,在这种情况下我希望它在下一次出现的时间19:24 - 1分钟内触发。

如果他们将警报设置为早上8点,我不希望它设置为当天的上午8点,但是在下一个上午8点 - 第二天设置。

如何让它针对下一次选择的时间?

3 个答案:

答案 0 :(得分:1)

假设闹钟时间为“小时”和“分钟”,则以下代码 应该产生预期的结果:

NSDate *now = [NSDate date];
// Example values for testing:
NSUInteger alarmHour = 10;
NSUInteger alarmMinute = 5;

// Compute alarm time by replacing hour/minute of the current time
// with the given values:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit
                                fromDate:now];
[comp setHour:alarmHour];
[comp setMinute:alarmMinute];
NSDate *alarm = [cal dateFromComponents:comp];

// If alarm <= now ...
if ([alarm compare:now] != NSOrderedDescending) {
    // ... add one day:
    NSDateComponents *oneDay = [[NSDateComponents alloc] init];
    [oneDay setDay:1];
    alarm = [cal dateByAddingComponents:oneDay toDate:alarm options:0];
}

答案 1 :(得分:0)

更简洁,@ HotLicks建议:

NSDate *userEnteredDate;
NSDate *now = [NSDate date];

if (now == [now laterDate:userEnteredDate]) {
    NSDateComponents *components = [[NSCalendar currentCalendar] components:255 fromDate:userEnteredDate];  // 255= the important component masks or'd together
    components.day += 1;
    userEnteredDate = [[NSCalendar currentCalendar] dateFromComponents:components];
}

答案 2 :(得分:-3)

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    NSDateFormatter *formatter_ = [[NSDateFormatter alloc]init];

    NSDate *alarmDate = [formatter dateFromString:@"enter your users alarm time-examle(2345)"];
    NSDate *currentDate = [NSDate date];

     [formatter setDateFormat:@"HHmm"];

    NSDate *finalDate;

    if ([[formatter stringFromDate:currentDate] intValue] > [[formatter stringFromDate:alarmDate] intValue]) {
        [formatter setDateFormat:@"HH:mm"];

        [formatter_ setDateFormat:@"dd MM yyyy"];


        NSDate *date = [currentDate dateByAddingTimeInterval:60*60*24*1];

        finalDate = [formatter_ dateFromString:[NSString stringWithFormat:@"%@ %@",[formatter stringFromDate:alarmDate],[formatter_ stringFromDate:date]]];
    }else{

        finalDate = [formatter_ dateFromString:[NSString stringWithFormat:@"%@ %@",[formatter stringFromDate:alarmDate],[formatter_ stringFromDate:currentDate]]];
    }