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

标签 ios swift nsdate

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

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

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

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

我尽量避免做这样的事情

伪代码: NSDate.date 小时分量 + (UTC_offset/60 = -7 小时)

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

        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.
        }

是否更容易偏移当前时间?

最佳答案

在您可以在日期操作中使用“打开”和“关闭”时间之前,您需要从已设置为这些时间的时区的日历创建一个 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

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

关于ios - 如何在没有硬编码手动计算的情况下使用 UTC 时区偏移量来偏移 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38457167/

相关文章:

ios - 将 PasswordField 设置为 secureTextEntry 给我一个奇怪的行为

ios - 如何向 XCUITest 添加标签/属性(Swift)

ios - 不支持指定多个 post_install Hook 的无效 Podfile 文件

ios - Xamarin iOS : Unable to set constraints on Controls from Visual Studio 2017

ios - 无法通过使用 UIWebView 点击播放按钮来启动嵌入式 Youtube 视频

ios - 'RefreshControl' 上的“数组索引超出范围”

ios - IOS中没有可见的@interface声明选择器 'ordinalityOfUnit:inUnit:forDate:'

ios - 在 coredata 中存储 NSdate 时出错

swift - Swift 中是否只有日期(没有时间)类?

ios - 如何知道请求是否来自缓存或不使用 AFNetworking