在 Swift 中获得正确的时间

Get the hour right in Swift

我正在尝试使用字符串到日期格式化程序,但一直出错。 像这样调用函数:

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