swift 如何获取时区偏移为±hh:mm?

2skhul33  于 2023-11-16  发布在  Swift
关注(0)|答案(6)|浏览(127)

我可以通过以下方式获得GMT的偏移秒数:TimeZone.current.secondsFromGMT()
但是,如何获得±hh:mm

k0pti3hp

k0pti3hp1#

一些整数运算来获得以小时和分钟为单位的偏移量:

let seconds = TimeZone.current.secondsFromGMT()

let hours = seconds/3600
let minutes = abs(seconds/60) % 60

字符串
印刷:

let tz = String(format: "%+.2d:%.2d", hours, minutes)
print(tz) // "+01:00"


%.2d打印一个(至少)有两个十进制数字的整数(如果需要的话,还可以加上前导零)。%+.2d%+.2d相同,但非负数的前导符号为+

dtcbnfnu

dtcbnfnu2#

这里是用于获取时区偏移差异和±hh:mm的扩展Swift 4| Swift 5代码

extension TimeZone {

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

    func offsetInHours() -> String
    {
    
        let hours = secondsFromGMT()/3600
        let minutes = abs(secondsFromGMT()/60) % 60
        let tz_hr = String(format: "%+.2d:%.2d", hours, minutes) // "+hh:mm"
        return tz_hr
    }
}

字符串

这样使用

print(TimeZone.current.offsetFromGMT()) // output is +0530
print(TimeZone.current.offsetInHours()) // output is "+05:30"

vqlkdk9b

vqlkdk9b3#

如果可以使用Date()

func getCurrentTimezone() -> String {
    let localTimeZoneFormatter = DateFormatter()
    localTimeZoneFormatter.dateFormat = "ZZZZZ"
    return localTimeZoneFormatter.string(from: Date())
}

字符串
将返回“+01:00”格式

ct2axkht

ct2axkht4#

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

Use like this

print(TimeZone.current.offsetFromUTC()) // output is +0530
print(TimeZone.current.currentTimezoneOffset()) // output is "+05:30"

字符串
根据时区,它在所有国家/地区100%工作。

rsaldnfx

rsaldnfx5#

Swift 4及以上

extension TimeZone {

    func timeZoneOffsetInHours() -> Int {
        let seconds = secondsFromGMT()
        let hours = seconds/3600
        return hours
    }
    func timeZoneOffsetInMinutes() -> Int {
        let seconds = secondsFromGMT()
        let minutes = abs(seconds / 60)
        return minutes
    }
}

字符串

deyfvvtc

deyfvvtc6#

接受的答案不能正确处理“-00:30”的情况,因为“+/-”只根据小时而不是分钟来确定。我会根据对初始秒值的检查来设置符号。或者你可以使用DateComponentsFormatter

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .positional
formatter.zeroFormattingBehavior = .pad
let interval: TimeInterval = TimeInterval.init(abs(secondsOffset))
let offsetValue: String = formatter.string(from: interval)

字符串

相关问题