如何将时区偏移量设为±hh:mm?

Tru*_*an1 13 timezone swift swift3

我可以通过以下方式获得GMT的偏移秒数:TimeZone.current.secondsFromGMT().

但是,我如何获得格式±hh:mm

Mar*_*n R 24

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

let seconds = TimeZone.current.secondsFromGMT()

let hours = seconds/3600
let minutes = abs(seconds/60) % 60
Run Code Online (Sandbox Code Playgroud)

格式化打印:

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

%.2d打印一个带(至少)两位小数的整数(必要时前导零).%+.2d是相同的,但有一个+非负数的前导符号.

  • @ammateja:“%+.2d”格式中的“+”仅在正数(和零)前面加上加号。负数仍以减号开头打印。 (3认同)

Nat*_*ali 8

如果你可以使用Date()

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

将返回“+01:00”格式


Nik*_*ani 5

这是获取时区偏移量差和±hh:mm的扩展Swift 4代码

extension TimeZone {

    func offsetFromUTC() -> 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
    }
}
Run Code Online (Sandbox Code Playgroud)

这样使用

print(TimeZone.current.offsetFromUTC()) // output is +0530
print(TimeZone.current.offsetInHours()) // output is "+05:30"
Run Code Online (Sandbox Code Playgroud)