3

NSDictionary に 2 回保存しました。「開始時間」は 22:30、「終了時間」は午前 4:00 です。

現在の時刻が開始時刻の前、終了時刻の前、または終了時刻の後、次の開始時刻がロールアラウンドする前のいずれであるかを把握する必要があります。

私はこれを必要以上に複雑にしていると確信していますが、すべての可能性を隠蔽しようとして、私は自分自身を完全に混乱させました.

NSDictionary *noaudio = [[NSUserDefaults standardUserDefaults] objectForKey:@"NoSound"];
NSDateFormatter *tformat = [[NSDateFormatter alloc] init];
[tformat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];  
[tformat setDateFormat:@"HH:mm"];

date1 = [tformat dateFromString:[noaudio objectForKey:@"start"]];
date2 = [tformat dateFromString:[noaudio objectForKey:@"end"]];
date3 = [NSDate date];

日付 1 と 2 の両方を 3 に対してチェックする必要がありますか?

これに関するガイダンスをありがとう。

4

2 に答える 2

1

時刻が 2 つだけで日付がないため、現在の時刻が開始時刻と終了時刻の間にあるかどうかしかわかりません。これは、上記の例 (開始時間 22:30 と終了時間 04:00) では、13:00 に何を返すのでしょうか? 今日は「終了時刻後」(04:00)「開始時刻前」(22:30)の両方です。

そうは言っても、現在の時刻が 2 つの日付で指定された時刻の間にあるかどうかを確認する 1 つの方法を次に示します。すべてを NSDate として (カレンダー操作を使用して) 保持することでこれを行うことができますが、指定された時間で今日の日付を使用して新しい NSDate オブジェクトを作成する必要があるため、さらに複雑になります。それほど難しくはありませんが、他の場所で使用していない限り、これを行う理由はありません。

// Take a date and return an integer based on the time.
// For instance, if passed a date that contains the time 22:30, return 2230
- (int)timeAsIntegerFromDate:(NSDate *)date {
    NSCalendar *currentCal      = [NSCalendar currentCalendar];
    NSDateComponents *nowComps  = [currentCal components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:date];
    return nowComps.hour * 100 + nowComps.minute;
}

// Check to see if the current time is between the two arbitrary times, ignoring the date portion:
- (BOOL)currentTimeIsBetweenTimeFromDate1:(NSDate *)date1 andTimeFromDate2:(NSDate *)date2 {
    int time1     = [self timeAsIntegerFromDate:date1];
    int time2     = [self timeAsIntegerFromDate:date2];
    int nowTime   = [self timeAsIntegerFromDate:[NSDate date]];

    // If the times are the same, we can never be between them
    if (time1 == time2) {
        return NO;
    }

    // Two cases:  
    // 1.  Time 1 is smaller than time 2 which means that they are both on the same day
    // 2.  the reverse (time 1 is bigger than time 2) which means that time 2 is after midnight
    if (time1 < time2) { 
        // Case 1
        if (nowTime > time1) {
            if (nowTime < time2) {
                return YES;
            }
        }
        return NO;
    } else { 
        // Case 2
        if (nowTime > time1 || nowTime < time2) {
            return YES;
        }
        return NO;
    }
}
于 2012-05-19T04:15:21.030 に答える
0

NSDate を NSDictionary に保存しないのはなぜですか? timeIntervalSinceReferenceDate次に、 orを使用して(実際には単なる double です) を取得し、簡単な比較を行うことtimeIntervalSince1970ができます。NSTimeInterval

時間がある場合、それらが同じ日付であるかどうかを判断することは不可能であるため、開始時間が真夜中より前で終了時間がそれ以降の場合に機能する一般的な解決策はわかりません...

いずれにせよ、 NSDate を格納するだけでなくても(これは本当ですか? 時間は外部ソースから来ているのでしょうか?)、double に変換して < と > だけを使用すると、作業がずっと簡単になります。

于 2012-05-18T23:43:31.180 に答える