代码之家  ›  专栏  ›  技术社区  ›  code-8

如何获得UTC和iPhone之间的时区偏移-Swift 4.2?

  •  1
  • code-8  · 技术社区  · 7 年前

    我在 Swift 4.2 .我正在努力获取UTC和iPhone上的时间之间的偏移时间。


    我有这个密码

    extension TimeZone {
        func offsetFromGMT() -> String
        {
            let localTimeZoneFormatter = DateFormatter()
            localTimeZoneFormatter.timeZone = self
            localTimeZoneFormatter.dateFormat = "Z"
            return localTimeZoneFormatter.string(from: Date())
        }
    }
    

    func getCurrentTimeZone() -> String{
        return String (TimeZone.current.identifier)
    }
    
    
    var tzOffset = ""
    let currentTimeZone = getCurrentTimeZone()
    TimeZone.knownTimeZoneIdentifiers.forEach({ timeZoneIdentifier in
        if let timezone = TimeZone(identifier: timeZoneIdentifier)
        {
            //print("\(timezone.identifier) \(timezone.offsetFromGMT())")
        
            if(timezone.identifier == currentTimeZone){
                tzOffset = timezone.offsetFromGMT()
            }
        }
    })
    

    后果

    如果我这样做了

    print(tzOffset)
    

    我得到了

    -0500
    

    应该是吗 -5 因为我现在的时区是 America/Montreal ?

    谁能给我个提示吗?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Leo Dabus    5 年前

    你可以得到当前时区,从格林威治标准时间得到秒数,然后除以3600。

    TimeZone.current.secondsFromGMT() / 3600    // -3 hs America/Sao_Paulo (current) Brazil
    

    如果你需要更高的精度,比如小时分数,只需在除以它之前将其转换为双倍。

        2
  •  1
  •   FullMetalFist vjking9    7 年前

    应该是的 -0500 .

    From the Wikipedia page

    它有4位数而不是1位数的原因是因为它是24小时格式的,并且一些时区是在距离UTC半小时的距离内测量的

    推荐文章