我正在从XML文件转换日期字段,这些日期存储在" yyyyMMddHHmmss"格式。当我使用DateFormmater的日期功能时,我没有得到正确的时间。因此,对于dateString" 20150909093700",它返回" 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
}
答案 0 :(得分:0)
@ 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), "]")
您正在获得“正确的时间”...您只是认为自己不是因为您正在查看该日期/时间的错误 字符串表示