2017-03-22 44 views
-1

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

这是我的代码:

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 

} 
+1

您正在添加时区'dateFormatter.timeZone = TimeZone(缩写:“EST”)'计算日期时使用此时区的偏移量。只是UTC时区。 – rckoenes

+1

@rckoenes OP的代码很好。他们只是误解了看'日期'值的输出。这已经在这里覆盖了很多次。 – rmaddy

+0

@rmaddy第二次阅读,你可能是对的。 – rckoenes

回答

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), "]") 

你得到了“正确的时间” ......你只是觉得你不是因为你看错字符串表示的该日期/时间

+0

解释。谢谢! – user30646