ios - Swift 5:在显示的时间更改时区
问题描述
我试图在 UILabel,Swift 5 中向我的用户显示当前时间。
我正在使用以下代码来显示当前时间,它有效:
import UIKit
class FlightViewController: UIViewController {
@IBOutlet weak var UTCTime: UILabel!
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
UTCTime.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .none)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
}
@objc func tick() {
UTCTime.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
}
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
这将显示设备设置中设置的区域的当前时间,但我想在 UILabel 中显示 UTC 的当前时间。但我根本不知道如何实现这一目标。
有没有人有一些指示?谢谢!
解决方案
在文档(讨论段落)中使用相同的代码并设置时区应该可以解决问题。
extension DateFormatter {
static func utcLocalizedString(from: Date, dateStyle: Style, timeStyle: Style) -> String {
let utcDateFormatter = DateFormatter()
utcDateFormatter.formatterBehavior = .behavior10_4
utcDateFormatter.dateStyle = dateStyle
utcDateFormatter.timeStyle = timeStyle
utcDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
return utcDateFormatter.string(from: from)
}
}
// example
let now = Date()
let nowAsString = DateFormatter.localizedString(from: now, dateStyle: .none, timeStyle: .short)
print(nowAsString) // 4:42 PM
let utcNowAsString = DateFormatter.utcLocalizedString(from: now, dateStyle: .none, timeStyle: .short)
print(utcNowAsString) // 2:42 PM
// usage in you view controller
import UIKit
class FlightViewController: UIViewController {
@IBOutlet weak var UTCTime: UILabel!
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
UTCTime.text = DateFormatter.utcLocalizedString(from: Date(), dateStyle: .none, timeStyle: .none)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
}
@objc func tick() {
UTCTime.text = DateFormatter.utcLocalizedString(from: Date(), dateStyle: .none, timeStyle: .short)
}
}
请注意,在示例中,每秒都会创建一个新的日期格式化程序;更好的方法是创建一个日期格式化程序(就像在扩展程序中所做的那样)并始终使用那个。
推荐阅读
- .htaccess - 将 RedirectMatch 更改为 OpenLiteSpeed 的 RewriteRule
- sql-server - 将两个不同的行合并为具有不同模式的SQL中的单行
- regex - vim regex : how to replace enclosing backticks with tags
- c++ - C ++如何知道对象何时被销毁
- javascript - Javascript 通过换行符或逗号匹配数字
- python - 重构手动连接循环
- java - 片段 Android Studio
- react-native - 如何在带有文本的react-native中创建进度条
- python-3.x - 转换多个字符串值(Python 3)
- c - 在 xcode 中为 macOS 使用 C 库