Swift datefomatter returns 时间错误

Swift datefomatter returns wrong time

我在 iOS 应用程序中工作 Dateformatter 这是 return 错误的时间。我不知道要解决这个问题。谁能纠正我以获得正确的时间?

let dateString = "2020-08-11T05:32:33.000Z"

func approach1(){
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
          
    guard let date = dateFormatter.date(from: dateString) else {fatalError()}
    
    printTime(date: date)
}

func approach2(){
    
    let dateFormatter = ISO8601DateFormatter()
    dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    guard let date = dateFormatter.date(from: dateString) else { fatalError()}
      
    printTime(date: date)
}

func printTime(date: Date){
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.amSymbol = "AM"
    dateFormatter.pmSymbol = "PM"
    let time  = dateFormatter.string(from: date)

    print("date: \(date)")
    print("Time: \(time)") // Here it's always wrong time with those approach.
}

当前结果:

您需要在格式化为字符串时指定时区(默认情况下使用您当前的本地时区):

func printTime(date: Date) {
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC") // <- add here
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.amSymbol = "AM"
    dateFormatter.pmSymbol = "PM"
    let time = dateFormatter.string(from: date)

    print("date: \(date)")
    print("Time: \(time)")
}

没什么问题。日期格式化程序 returns 正确时间

日期字符串

"2020-08-11T05:32:33.000Z"

表示 UTC 日期 (+0000)。

你当地的时区显然是UTC+0530。 DateFormatter 默认考虑本地时区。

要在 UTC 中格式化 time,您必须明确设置日期格式化程序的时区

func printTime(date: Date) {
    
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(identifier: "UTC")
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.amSymbol = "AM"
    dateFormatter.pmSymbol = "PM"
    let time  = dateFormatter.string(from: date)

    print("date: \(date)")
    print("Time: \(time)")
}

默认情况下,dateFormatter 使用本地时区。要正确显示,请将其时区设置为 UTC:dateFormatter.timeZone = TimeZone(abbreviation: "UTC")