Check if there is time before or after two saved lines of the text line

I stored it twice in NSDictionary. "Start time" is 22:30, and "End time" is 4:00.

I need to find out if the current time is before the start time, before the end of the time, or after the end of the time and until the next start time.

I am sure that I am doing it a lot harder than it should be, but trying to cover all the possibilities that I completely confused.

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];

Should I check both date 1 and 2 against 3?

Thanks for any advice on this.

+3
source share
2 answers

, , , . , ( 22:30 04:00), 13:00? "(04:00) " "(22:30) .

, , , . , 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;
    }
}
+1

NSDate NSDictionary? timeIntervalSinceReferenceDate timeIntervalSince1970, NSTimeInterval ( ) .

, , , , , ...

, NSDate ( ? , - ?), , < > .

0

All Articles