1

I try to obtain the actual time of the CEST-Timezone in my Swift4-code in the following format

"HH:mm" // needed in CEST TimeZone (CEST = Central European Summer Time)

There are two strange behaviours I observe when trying to do so (see Code below...):

1.) when TimeZone-identifier is set to CEST --> then the received HH:mm is completely wrong (and is rather in the UTC than expected CEST timezone)

2.) when TimeZone-Identifier is set to "CET" (instead of CEST) --> then everything works ! (i.e. the received HH:mm time is the correct CEST-time (surprisingly - it is not in the expected CET-timezone but rather in the CEST-timezone)

The TimeZone I set my iPhone during the testing is set to PDT (= UTC-7)... But also other TimeZones do show the strange behaviour observed...

Here is my Code (see CEST vs. CET setting)

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

using the following extension on Date and String :

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

1 回答 1

-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
于 2018-04-17T14:44:00.833 回答