【问题标题】:IOS - Get Current TimeZone of Device in GMT formatIOS - 以 GMT 格式获取设备的当前时区
【发布时间】:2016-04-26 09:12:51
【问题描述】:

我在谷歌上搜索了很多关于这个问题,但没有找到合适的解决方案。所有结果以日期和时间格式给出时区。

我想知道如何仅获取 GMT 格式的设备时区。 就像,我只想要这个

+5:30

作为时区。我怎样才能做到这一点?

我试过了

 NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];

但它会在 kolkatta/Delhi 给出结果。 我也尝试了其他答案,但没有找到解决方案。

【问题讨论】:

    标签: ios objective-c timezone gmt


    【解决方案1】:

    我的建议是查看 NSTimeZone 的 Apple 文档。

    如果你这样做了,你就会意识到有一个方法 -secondsFromGMT 可以返回格林威治时间的秒数。
    也许您还可以创建自己的date formatter 字符串作为NSDateFormatter-dateFormat 属性传递,并直接获取时区的字符串表示形式。类似@"ZZZZZ".
    点击here 了解如何正确编码日期格式。

    【讨论】:

    • 创建一个仅返回 GMT 偏移量的日期格式化程序听起来是正确的解决方案。 (已投票。)这样您就不必担心繁琐的格式问题。日期格式化程序会为您完成。
    【解决方案2】:

    试试这个:

        NSDate *myDate = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateStyle:NSDateFormatterLongStyle];
        [dateFormatter setTimeStyle:NSDateFormatterLongStyle];
        [dateFormatter setDateFormat:@"ZZZ"];
    
         NSTimeZone *timeZone = [NSTimeZone timeZoneWithName: @"Asia/Kolkata"];
        [dateFormatter setTimeZone:timeZone];
    
        NSString *dateString = [dateFormatter stringFromDate: myDate];
        NSLog(@"%@", dateString);
    

    输出:

    +0530

    有关更多信息,请阅读@Andrea 答案

    【讨论】:

      【解决方案3】:
      -(void)getCurrentTimeZoneMins
      {
          NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
          float timeZoneOffset = [destinationTimeZone secondsFromGMTForDate:[NSDate date]] / 60;;
          NSLog(@"%f mins",timeZoneOffset);
      }
      
      -(void)printTimeZone
      {
          NSDateFormatter *localTimeZoneFormatter = [NSDateFormatter new];
          localTimeZoneFormatter.timeZone = [NSTimeZone localTimeZone];
          localTimeZoneFormatter.dateFormat = @"Z";
          NSString *localTimeZoneOffset = [localTimeZoneFormatter stringFromDate:[NSDate date]];
          NSLog(@"%@",localTimeZoneOffset);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 2010-10-05
        • 2015-01-03
        • 2012-10-29
        • 2016-03-01
        • 2020-08-17
        • 1970-01-01
        相关资源
        最近更新 更多