简体   繁体   中英

Converting a full date into just hours and minutes - Swift

I'm trying to do something very simple here and failing miserably. I just want to convert a string with a complete date into just the hours and minutes, can anyone see where I am going wrong? The following code prints nil

let dateString2 = "2018-03-11 20:43:05 +0000"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")


let dateObj = dateFormatter.date(from: dateString2)

dateFormatter.dateFormat = "hh:mm"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

Your dateFormat String is flawed. hh is the 12hour time format, when you clearly receive a 24h time format, for which you need to use HH . Even though zzzz works, +0000 should actually be represented by z . When working with fixed time formats in most cases you should also set the locale to en_US_POSIX .

let dateString2 = "2018-03-11 20:43:05 +0000"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")

let dateObj = dateFormatter.date(from: dateString2)
dateFormatter.dateFormat = "HH:mm"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

Output:

20:43

You need HH (24-hour) for the hour, not hh (12-hour). You also need to use the special locale of en_US_POSIX , not en_GB . You should also use Z for the timezone, not +zzzz .

let dateString2 = "2018-03-11 20:43:05 +0000"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")


if let dateObj = dateFormatter.date(from: dateString2) {
    dateFormatter.dateFormat = "HH:mm" // or "hh:mm a"
    print("Dateobj: \(dateFormatter.string(from: dateObj))")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM