Determine if current local time is between two times (ignoring the date portion)

后端 未结 3 450
礼貌的吻别
礼貌的吻别 2021-01-06 05:59

Considering that there is no NSTime in Cocoa-Touch (Objective-C on iPhone), and given two times as NSStrings and a timezone as an NSString, how can you calculate whether or

相关标签:
3条回答
  • 2021-01-06 06:01

    You should probably look at NSCalendar and NSDateComponents. I'm using them to do some date math for an iPhone app. I don't see a builtin method to do what you want directly, but you can figure it out by breaking it into pieces I expect?

    0 讨论(0)
  • 2021-01-06 06:07

    You should be able to do what you are wanting to do with a combination of NSDate, and NSDateFormatter.

    NSDateFormatter has a dateFromString: method which will let you convert your strings into NSDate objects, then you can use the compare: method of NSDate to compare the two against [NSDate date] which will have the current time.

    (NSDate encompasses both date and time)

    0 讨论(0)
  • 2021-01-06 06:12

    The biggest problem with this seems to come from the fact that the times may span two days (originally they might not, but when you do the timezone conversion, after that they might). So if we're to ignore the given date information completely, some assumptions have to be made with how to handle these date spans. Your question isn't exact on how to deal with this (i.e. I don't know exactly what you'd like to achieve) so here's just one way to go about it, which might not be exactly what you're after, but hopefully it will guide you in the right direction:

    • Parse the given strings to NSDate objects, ignoring the date information (result: times are handled such that they're assumed to be for the same day) and performing the time zone conversion
    • Get the time interval from the earlier NSDate to the later NSDate
    • Create NSDate objects for "today at the earlier given time" and "yesterday at the earlier given time"
    • Compare the time intervals from these two NSDates till the current date/time to the time interval between the two given date/times

    Also note that time zone strings in the format you gave ("Pacific Time (US & Canada)") will not be understood by NSTimeZone so you'll need to do some conversion there.

    Here's a code example (I wrote this on OS X since I don't have the iPhone SDK so hopefully all the used APIs will be available on iPhone as well):

    - (BOOL)checkTimes
    {
        // won't work:
        //NSString *tzs = @"Pacific Time (US & Canada)";
        // 
        // will work (need to translate given timezone information
        // to abbreviations accepted by NSTimeZone -- won't cover
        // that here):
        NSString *tzs = @"PST";
    
        NSString *ds1 = @"2000-01-01T10:00:00Z";
        NSString *ds2 = @"2000-01-01T17:00:00Z";
    
        // remove dates from given strings (requirement was to ignore
        // the dates completely)
        ds1 = [ds1 substringFromIndex:11];
        ds2 = [ds2 substringFromIndex:11];
    
        // remove the UTC time zone designator from the end (don't know
        // what it's doing there since the time zone is given as a
        // separate field but I'll assume for the sake of this example
        // that the time zone designator for the given dates will
        // always be 'Z' and we'll always ignore it)
        ds1 = [ds1 substringToIndex:8];
        ds2 = [ds2 substringToIndex:8];
    
        // parse given dates into NSDate objects
        NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
        [df setDateFormat:@"HH:mm:ss"];
        [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:tzs]];
        NSDate *date1 = [df dateFromString:ds1];
        NSDate *date2 = [df dateFromString:ds2];
    
        // get time interval from earlier to later given date
        NSDate *earlierDate = date1;
        NSTimeInterval ti = [date2 timeIntervalSinceDate:date1];
        if (ti < 0)
        {
            earlierDate = date2;
            ti = [date1 timeIntervalSinceDate:date2];
        }
    
        // get current date/time
        NSDate *now = [NSDate date];
    
        // create an NSDate for today at the earlier given time
        NSDateComponents *todayDateComps = [[NSCalendar currentCalendar]
                                            components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                            fromDate:now];
        NSDateComponents *earlierTimeComps = [[NSCalendar currentCalendar]
                                              components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit
                                              fromDate:earlierDate];
        NSDateComponents *todayEarlierTimeComps = [[[NSDateComponents alloc] init] autorelease];
        [todayEarlierTimeComps setYear:[todayDateComps year]];
        [todayEarlierTimeComps setMonth:[todayDateComps month]];
        [todayEarlierTimeComps setDay:[todayDateComps day]];
        [todayEarlierTimeComps setHour:[earlierTimeComps hour]];
        [todayEarlierTimeComps setMinute:[earlierTimeComps minute]];
        [todayEarlierTimeComps setSecond:[earlierTimeComps second]];
        NSDate *todayEarlierTime = [[NSCalendar currentCalendar]
                                    dateFromComponents:todayEarlierTimeComps];
    
        // create an NSDate for yesterday at the earlier given time
        NSDateComponents *minusOneDayComps = [[[NSDateComponents alloc] init] autorelease];
        [minusOneDayComps setDay:-1];
        NSDate *yesterday = [[NSCalendar currentCalendar]
                             dateByAddingComponents:minusOneDayComps
                             toDate:now
                             options:0];
        NSDateComponents *yesterdayDateComps = [[NSCalendar currentCalendar]
                                                components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                                fromDate:yesterday];
        NSDateComponents *yesterdayEarlierTimeComps = [[[NSDateComponents alloc] init] autorelease];
        [yesterdayEarlierTimeComps setYear:[yesterdayDateComps year]];
        [yesterdayEarlierTimeComps setMonth:[yesterdayDateComps month]];
        [yesterdayEarlierTimeComps setDay:[yesterdayDateComps day]];
        [yesterdayEarlierTimeComps setHour:[earlierTimeComps hour]];
        [yesterdayEarlierTimeComps setMinute:[earlierTimeComps minute]];
        [yesterdayEarlierTimeComps setSecond:[earlierTimeComps second]];
        NSDate *yesterdayEarlierTime = [[NSCalendar currentCalendar]
                                    dateFromComponents:yesterdayEarlierTimeComps];
    
        // check time interval from [today at the earlier given time] to [now]
        NSTimeInterval ti_todayEarlierTimeTillNow = [now timeIntervalSinceDate:todayEarlierTime];
        if (0 <= ti_todayEarlierTimeTillNow && ti_todayEarlierTimeTillNow <= ti)
            return YES;
    
        // check time interval from [yesterday at the earlier given time] to [now]
        NSTimeInterval ti_yesterdayEarlierTimeTillNow = [now timeIntervalSinceDate:yesterdayEarlierTime];
        if (0 <= ti_yesterdayEarlierTimeTillNow && ti_yesterdayEarlierTimeTillNow <= ti)
            return YES;
    
        return NO;
    }
    
    0 讨论(0)
提交回复
热议问题