0
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分钟
- 12
秒 - 0
最终日期 - 2017-10-08 00:12:00 +0000
但我的预期日期应该是
最终日期 - 2017-10-07 20:12 :00 +0000

4

1 回答 1

0

我得到了解决方案,@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

于 2017-10-11T04:51:43.703 回答