let dateString = "2017-10-08T00:12:00.000Z"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
let date = formatter.date(from: dateString)!
let components = Calendar.current.dateComponents(in: TimeZone(identifier: "America/New_York")!, from: date)
print("Day - \(components.day!)")
print("Month - \(components.month!)")
print("Year - \(components.year!)")
print("Hour - \(components.hour!)")
print("Min - \(components.minute!)")
print("Second - \(components.second!)")
print("Final Date - \(components.date!)")
通过运行上面的代码,我得到了输出
日 - 7
月 - 10
年 - 2017年 小时 - 20
Min - 12
第二 - 0
截止日期 - 2017-10-08 00:12:00 +0000
但是我的预期日期应该是 截止日期 - 2017-10-07 20:12:00 +0000
答案 0 :(得分:0)
I GOT SOLUTION AS @Leo Dabus说时区问题
let dateString = "2017-10-08T00:12:00.000Z"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
let date = formatter.date(from: dateString)!
let components = Calendar.current.dateComponents(in: TimeZone(identifier: "America/New_York")!, from: date)
//Converting part
let gregorian = Calendar(identifier: .gregorian)
var dateComponents = components
dateComponents.timeZone = TimeZone.init(identifier: "UTC") //Here is the logic
let myDate = gregorian.date(from: dateComponents)!
print(myDate)
现在我将转换日期作为输出。 2017-10-07 20:12:00 +0000