如何将时区偏移量设为 ±hh:mm? [英] How to get timezone offset as ±hh:mm?

查看:35
本文介绍了如何将时区偏移量设为 ±hh:mm?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以从 GMT 获取偏移秒数:TimeZone.current.secondsFromGMT().

I can get the offset seconds from GMT with this: TimeZone.current.secondsFromGMT().

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

However, how do I get the format as ±hh:mm?

推荐答案

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

Some integer arithmetic to obtain the offset in hours and minutes:

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 prints an integer with (at least) two decimal digits (and leading zero if necessary). %+.2d is the same but with a leading + sign for non-negative numbers.

这篇关于如何将时区偏移量设为 ±hh:mm?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆