首页 > 解决方案 > 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 的当前时间。但我根本不知道如何实现这一目标。

有没有人有一些指示?谢谢!

标签: iosswiftxcodedatetime

解决方案


在文档(讨论段落)中使用相同的代码并设置时区应该可以解决问题。

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)
    }
}

请注意,在示例中,每秒都会创建一个新的日期格式化程序;更好的方法是创建一个日期格式化程序(就像在扩展程序中所做的那样)并始终使用那个。


推荐阅读