假设当前本地时间是 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/