0

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

如果他们将闹钟设置为上午 8 点,我不希望它设置为当天上午 8 点,而是设置为下一个上午 8 点 - 第二天。

我怎样才能让它瞄准所选时间的下一次出现?

4

3 回答 3

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];
}
于 2013-09-04T19:07:51.633 回答
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];
}
于 2013-09-04T19:19:15.517 回答
-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]]];
    }
于 2013-09-04T18:48:49.730 回答