【问题标题】:Time Zones and Offset from specific Hour时区和特定小时的偏移量
【发布时间】:2015-04-15 21:52:41
【问题描述】:

我试图让用户在他们各自的当地时间获得时间,因为它是从一天中的特定时间开始的。

例如,小时是恒定的,UTC 下午 4 点

字符串将如下所示:

您的包裹将在 UTC 时间晚上 11 点准备好(用户时间以小时/一天中的时间 + 本地时间缩写)

所以:

您的包裹将在世界标准时间晚上 11 点(美国东部标准时间晚上 7 点)准备好

我很难从世界标准时间晚上 11 点开始计算时间。

这是我所拥有的:

float timezoneoffset = ([[NSTimeZone systemTimeZone] secondsFromGMT] /3600.0);
//Gets time zone hours away from GMT/UTC time in this case -4

我知道如何获取自 date 以来的日期,但在我的情况下,它始终是 11PM UTC 或任何设置的数字。那么如何从任何一天的某个特定时间获取日期(但始终保持不变,始终是晚上 11 点或其他时间)

【问题讨论】:

    标签: ios nsdate nsdateformatter


    【解决方案1】:

    在玩了几个小时后,这就是我想出的。

    [NSDate date]
    

    默认情况下自动为 UTC 或 GMT 时间。所以从那里我只是使用NSDateComponents 来强制在我想要的时间开始日期并从 timezoneoffset 值中减去/添加:

     float timezoneoffset = [[NSTimeZone systemTimeZone] secondsFromGMT];
    
        NSDateComponents *components = [[NSDateComponents alloc] init];
        [components setHour:23];
        [components setMinute:0];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    
        NSDate *maintenanceDateTime = [calendar dateFromComponents:components];
        NSDate *localTimeFromUTC = [NSDate dateWithTimeInterval:timezoneoffset sinceDate:maintenanceDateTime];
    
        NSDateFormatter *utc_formatter = [[NSDateFormatter alloc] init];
        [utc_formatter setDateFormat:@"HHmm"];
        [utc_formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 2020-08-05
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 2011-07-02
      • 2011-09-02
      • 2021-12-01
      • 2014-02-04
      相关资源
      最近更新 更多