Swift 5: изменить часовой пояс в отображаемом времени - PullRequest
1 голос
/ 04 мая 2020

Я пытаюсь показать текущее время моему пользователю в 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.
    }
    */

Здесь отображается текущее время для региона, установленного в настройках устройства, но я бы хотел отобразить текущее время для UT C в UILabel. Но я просто не могу понять, как этого добиться.

У кого-нибудь есть указатели? Спасибо!

1 Ответ

0 голосов
/ 04 мая 2020

Использование того же кода в документации (абзац обсуждения) и установка часового пояса должны помочь.

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

Обратите внимание, что в примере каждую секунду новая дата форматтер создан; лучшим подходом было бы создать один форматер даты (как это было сделано в расширении) и всегда использовать его.

...