如何在没有硬编码手动计算的情况下使用 UTC 时区偏移量来偏移 NSDate

How to offset NSDate with UTC timezone offset without hardcoded manual calculation

假设当前本地时间是 15:11 UTC。我从服务器中检索了一个数据集,该数据集显示了一家公司的营业时间,如下所示:

{
close = {
   day = 3;
   time = 0200;
};
open = {
   day = 2;
   time = 1700;
};

我还收到一个 utc-offset 属性 暴露如下:"utc_offset" = "-420”; 我想这是一个分钟偏移,给出 7 小时的小时偏移,考虑到我所在的时区,这似乎是正确的是 UTC,我收到的营业地点的营业时间信息是洛杉矶一家营业时间晚 7 小时的信息。

我如何使用这个 属性 然后能够对其进行任何时间计算 我想确定当前本地时间是否落在我计算出的开盘时间和闭盘时间之间,但是考虑到时间比较是在本地时区完成的,当它需要在针对该时间范围进行计算之前进行偏移时,计算结果是错误的.

我正在努力避免做类似

的事情

伪代码: NSDate.date hour componenent + (UTC_offset / 60 = -7 hours)

更新: 这是我目前检查商家是否现在营业的方式

        if currentArmyTime.compare(String(openInfo.time)) != .OrderedAscending && currentArmyTime.compare(String(closeInfo.time)) != .OrderedDescending {
            //The business is open right now, though this will not take into consideration the business's time zone offset.
        }

偏移当前时间更容易吗?

在日期操作中使用 'open' 和 'close' 时间之前,您需要从已设置为这些时间时区的日历创建 NSDate。这是一个例子:

// Create calendar for the time zone
NSInteger timeOffsetInSeconds = -420 * 60;
NSTimeZone *tz = [NSTimeZone timeZoneForSecondsFromGMT:timeOffsetInSeconds];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
calendar.timeZone = tz;

// Create an NSDate from your source data
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = 1;
comps.month = 1;
comps.year = 2016;
comps.hour = 8;
comps.minute = 0;
NSDate *openTime = [calendar dateFromComponents:comps];

// 'openTime' can now be to compared with local time.
NSLog(@"openTime = %@", openTime);  // Result is openTime = 2016-01-01 15:00:00 +0000

您应该将上述代码放入一个接受原始时间和要应用的时间偏移的方法中。