确定当前本地时间是否介于两次之间(忽略日期部分) [英] Determine if current local time is between two times (ignoring the date portion)

查看:94
本文介绍了确定当前本地时间是否介于两次之间(忽略日期部分)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到Cocoa-Touch(iPhone上的Objective-C)没有NSTime,并且NSStrings和NSZtring的时区分别是两次,你如何计算当前LOCAL时间是否在这两次之间。请记住,时间字符串中的日期并不重要,并且填充了虚拟日期。

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 not the current LOCAL time is between these two times. Keep in mind that the date in the time strings do NOT matter, and are filled with dummy dates.

例如:

 TimeZone: Pacific Time (US & Canada)
 Start Time: 2000-01-01T10:00:00Z
 End Time: 2000-01-01T17:00:00Z

 Local Time: now

你如何确认本地时间是否在指定的时间范围之间(确保首先将开始/结束时间转换为正确的时区)?

How do you confirm whether or not local time is between the time range specified (ensuring to convert the start/end times to the proper timezone first)?

推荐答案

这个问题的最大问题似乎来自时间可能跨越两天(原来他们可能没有,但是当你进行时区转换时,他们可能会这样)。因此,如果我们完全忽略给定的日期信息,则必须对如何处理这些日期跨度做出一些假设。你的问题并不是关于如何处理这个问题的确切问题(即我不确切地知道你想要实现什么)所以这里只是一种方法,这可能不是你所追求的,但是希望它能引导你朝着正确的方向发展:

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:


  • 将给定的字符串解析为 NSDate 对象,忽略日期信息(结果:处理时间使得它们被假定为同一天)并执行时区转换

  • 从早期获取时间间隔 NSDate 到后来的 NSDate

  • 创建 NSDate 的对象今天早些时候昨天在给定时间

  • 比较这两个 NSDate 的时间间隔,直到当前日期/时间到两个给定日期/时间之间的时间间隔

  • 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

另请注意您提供的格式的时区字符串(Paci时间(美国和美国) NSTimeZone 将无法理解加拿大)>,因此您需要在那里进行一些转换。

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.

这是一个代码示例(我在OS X上写了这个,因为我没有iPhone SDK所以希望所有使用过的API也可以在iPhone上使用)

- (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;
}

这篇关于确定当前本地时间是否介于两次之间(忽略日期部分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆