我尝试以下列格式在Swift4代码中获取CEST-Timezone的实际时间
"HH:mm" // needed in CEST TimeZone (CEST = Central European Summer Time)
我尝试这样做时有两种奇怪的行为(参见下面的代码......):
1。)当TimeZone-identifier设置为CEST时 - >然后收到的HH:mm是完全错误的(而且是在UTC中而不是预期的CEST时区)
2.)当TimeZone-Identifier设置为“CET”(而不是CEST)时 - >一切顺利! (即收到的HH:mm时间是正确的CEST时间(令人惊讶的是 - 它不在预期的CET时区,而是在CEST时区)
TimeZone我在测试过程中将我的iPhone设置为PDT(= UTC-7)......但是其他TimeZones确实显示了观察到的奇怪行为......
这是我的代码(请参阅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)
}
}
答案 0 :(得分:-1)
我已更新您的代码。请看一下:
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