我试图以下面的格式用Swift4代码获取CEST时区的实际时间
"HH:mm" // needed in CEST TimeZone (CEST = Central European Summer Time)
在尝试这样做时,我观察到两种奇怪的行为(见下面的代码…):
1.)当时区标识符设置为CEST-->时,收到的HH:mm是完全错误的(而不是在UTC中,而不是预期的CEST时区中)
2.)当时区标识符设置为“CET”(而不是CEST)时-->一切正常!(即,收到的HH:mm时间是正确的CEST时间(令人惊讶的是,它不在预期的CET时区,而是在CEST时区)
我在测试期间设置的iPhone时区设置为PDT(=UTC-7)。。。但其他时区也显示了观察到的奇怪行为。。。
这是我的代码(见CEST与CET设置)

let currentDate = Date()
let timeNowInCEST = currentDate.CurrentDate_to_CEST_timeOnlyString

在日期和字符串上使用以下扩展名:
extension Date {

    struct Formatter {
        static let CEST_TimeOnly_Formatter: DateFormatter = {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "HH:mm"

            // ******** here I set the CEST or CET timezone
            // setting it to CEST delivers UTC
            // setting it to CET delivers CEST
            // (both are wrong - why is this strange behaviour ?????????????????)
            // **************************************************

            // dateFormatter.timeZone = TimeZone(identifier: "CEST")
            dateFormatter.timeZone = TimeZone(identifier: "CET")

            return dateFormatter
        }()
    }

    var CurrentDate_to_CEST_timeOnlyString: String {
        let CurrentDateString = Formatter.localFormatter.string(from: self)
        let CEST_Date = CurrentDateString.dateFromLocal
        let CEST_DateString = Formatter.CEST_TimeOnly_Formatter.string(from: CEST_Date!)
        return CEST_DateString
    }
}

extension String {

    struct Formatter {
        static let localFormatter: DateFormatter = {
            let dateFormatter = DateFormatter()
            dateFormatter.timeZone = TimeZone.current
            dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
            return dateFormatter
        }()
    }

    var dateFromLocal: Date? {
        return Formatter.localFormatter.date(from: self)
    }
}

最佳答案

我已经更新了你的代码。请看一下:

extension Date {

    static let CEST_TimeOnly_Formatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        dateFormatter.timeZone = TimeZone(identifier: "CET")
        return dateFormatter
    }()

    var CurrentDate_to_CEST_timeOnlyString: String {
        let CEST_DateString = Date.CEST_TimeOnly_Formatter.string(from: self)
        return CEST_DateString
    }
}

按区域获取时间:
let currentDate = Date()
let timeNowInCEST = currentDate.CurrentDate_to_CEST_timeOnlyString

关于swift - CEST时间,格式为HH:mm,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49880570/

10-11 01:12