从 dateformatter 获取错误的时间

Getting wrong time from dateformatter

我正在从 XML 文件转换日期字段,这些日期以 "yyyyMMddHHmmss" 格式存储。当我使用 DateFormmater 的日期函数时,我没有得到正确的时间。因此,对于 dateString“20150909093700”,它 returns“2015-09-09 13:37:00 UTC”而不是“2015-09-09 09:37:00”。我在存储到 Core Data NSDate 字段之前进行这种转换。

这是我的代码:

static func stringToDate(DateString dateString: String) -> NSDate? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyyMMddHHmmss"
    dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "EST")

    if let date = dateFormatter.date(from: dateString) {
        return date as NSDate?
    }

    return nil

}

@user30646 -- 看看这是否有意义。使用您的确切函数:

func stringToDate(DateString dateString: String) -> NSDate? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyyMMddHHmmss"
    dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "EST")

    if let date = dateFormatter.date(from: dateString) {
        return date as NSDate?
    }

    return nil

}

let dateString = "20150909093700"

let returnedDate = stringToDate(DateString: dateString)

print("Date without formatting or Time Zone: [", returnedDate ?? "return was nil", "]")

let dFormatter = DateFormatter()
dFormatter.timeZone = TimeZone(abbreviation: "EST")
dFormatter.dateStyle = .full
dFormatter.timeStyle = .full

print("Result with formatting and Time Zone: [", dFormatter.string(from: returnedDate as! Date), "]")

你得到的是 "correct time" ...你只是认为你不是因为你看错了 字符串表示 其中 date/time.