我正在尝试使用String to Date格式程序,但一直搞错了。像这样调用函数:
self.stringToDate(date: "26 10 1995 10:54:00")
这是功能:
func stringToDate(date: String) -> Date {
print(date)
let formatter4 = DateFormatter()
formatter4.dateFormat = "dd MM yyyy HH:mm:ss"
return formatter4.date(from: date)!
}
这是控制台中的结果:
26 10 1995 10:54:00
1995-10-26 16:54:00 +0000
检查
import Foundation
let form = DateFormatter()
form.dateFormat = "dd MM yyyy HH:mm:ss"
print(form.timeZone, form.date(from: "26 10 1995 10:54:00") ?? "")
form.timeZone = TimeZone(abbreviation: "UTC")
print(form.timeZone, form.date(from: "26 10 1995 10:54:00") ?? "")
form.timeZone = TimeZone(abbreviation: "EST")
print(form.timeZone, form.date(from: "26 10 1995 10:54:00") ?? "")
打印
Optional(Europe/Bratislava (current)) 1995-10-26 09:54:00 +0000
Optional(GMT (fixed)) 1995-10-26 10:54:00 +0000
Optional(America/New_York (fixed)) 1995-10-26 14:54:00 +0000