【问题标题】:Converting UTC date format to local nsdate将 UTC 日期格式转换为本地 nsdate
【发布时间】:2015-06-06 05:21:05
【问题描述】:

我从服务器获取 UTC 时区的字符串日期,我需要将其转换为本地时区。

我的代码:

let utcTime = "2015-04-01T11:42:00.269Z"    
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = dateFormatter.dateFromString(utcTime)
println("utc: \(utcTime), date: \(date)")

这个打印 -

UTC:2015-04-01T11:42:00.269Z,日期:可选(2015-04-01 11:42:00 +0000)

如果我删除

dateFormatter.timeZone = NSTimeZone(name: "UTC") 

打印出来

UTC:2015-04-01T11:42:00.269Z,日期:可选(2015-04-01 08:42:00 +0000)

我的本​​地时区是 UTC +3 在第一个选项中我得到 UTC 在第二个选项中,我得到 UTC -3

我应该得到

UTC:2015-04-01T11:42:00.269Z,日期:可选(2015-04-01 14:42:00 +0000)

那么如何将 UTC 日期格式转换为本地时间呢?

【问题讨论】:

  • 你试过 formatter.timeZone = NSTimeZone.localTimeZone()
  • 是的,我得到 UTC -3 ... UTC:2015-04-01T11:42:00.269Z,日期:可选(2015-04-01 08:42:00 +0000)跨度>
  • @ilan 我在 swift 中也面临同样的问题。你能帮我解决这个问题吗?
  • @Rakesh 查看下面的答案,它们对我有用。

标签: ios swift date timezone nsdate


【解决方案1】:

以下内容在 Objective-C 中对我有用:

// create dateFormatter with UTC time format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [dateFormatter dateFromString:@"2015-04-01T11:42:00"]; // create date from string

// change to a readable time format and change to local time zone
[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];

我保留了这两个网站来方便地转换不同的时间格式: http://www.w3.org/TR/NOTE-datetime

http://benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/

在 Swift 中它将是:

// create dateFormatter with UTC time format
  let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        let date = dateFormatter.date(from: "2015-04-01T11:42:00")// create   date from string

        // change to a readable time format and change to local time zone
        dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
        dateFormatter.timeZone = NSTimeZone.local
        let timeStamp = dateFormatter.string(from: date!)

【讨论】:

  • 在 swift3 中,相当于:dateFormatter.timezone = TimeZone.current
  • let date = dateFormatter.dateFromString("2015-04-01T11:42:00") 当我在设备设置中设置 12 小时时间格式时,这会将 nil 分配给日期。
  • 当您转换回日期时,它会在 UTC 中再次给出。
【解决方案2】:

试试这个 Swift 扩展

Swift 4:UTC/GMT ⟺ 本地(当前/系统)

extension Date {

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

}


// Try it
let utcDate = Date().toGlobalTime()
let localDate = utcDate.toLocalTime()

print("utcDate - \(utcDate)")        //Print UTC Date
print("localDate - \(localDate)")     //Print Local Date

【讨论】:

  • @Krunal,我喜欢它的简单性,但是当我运行它时:public func runDatesExample() { let now = Date() let utcDate = now.toGlobalTime() let localDate = now.toLocalTime() print(now) //prints: 2020-04-08 00:31:17 +0000. //actual GMT/UTC right now print("utcDate - \(utcDate)") //prints: utcDate - 2020-04-08 06:31:17 +0000 print("localDate - \(localDate)") //prints: localDate - 2020-04-07 18:31:17 +0000 } 我希望utcDate 的输出与now 相同。我错过了什么吗?
【解决方案3】:

Swift 版本的 c_rath 答案:

// create dateFormatter with UTC time format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-04-01T11:42:00")

// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.localTimeZone() 
let timeStamp = dateFormatter.stringFromDate(date!)

【讨论】:

  • 第 5 行应为:dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a",第 6 行应为:dateFormatter.timeZone = NSTimeZone.localTimeZone()
【解决方案4】:

我不得不从 c_rath 解决方案中删除 z 和毫秒。在 swift 4 中工作。

extension String {
    func fromUTCToLocalDateTime() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        var formattedString = self.replacingOccurrences(of: "Z", with: "")
        if let lowerBound = formattedString.range(of: ".")?.lowerBound {
            formattedString = "\(formattedString[..<lowerBound])"
        }

        guard let date = dateFormatter.date(from: formattedString) else {
            return self
        }

        dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
        dateFormatter.timeZone = TimeZone.current
        return dateFormatter.string(from: date)
    }
}

【讨论】:

    【解决方案5】:

    在 Swift 3 中这很好用:

    // create dateFormatter with UTC time format
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    let date = dateFormatter.date(from: "2015-04-01T11:42:00")// create date from string
    
    // change to a readable time format and change to local time zone
    dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
    dateFormatter.timeZone = TimeZone.current
    let timeStamp = dateFormatter.string(from: date!)
    

    【讨论】:

      【解决方案6】:

      扩展其他人提到的内容,这里有一个方便的 NSDate Swift 扩展

      import Foundation
      
      extension NSDate {
          func ToLocalStringWithFormat(dateFormat: String) -> String {
              // change to a readable time format and change to local time zone
              let dateFormatter = NSDateFormatter()
              dateFormatter.dateFormat = dateFormat
              dateFormatter.timeZone = NSTimeZone.localTimeZone()
              let timeStamp = dateFormatter.stringFromDate(self)
      
              return timeStamp
          }
      }
      

      【讨论】:

        【解决方案7】:

        也许您可以尝试以下方法:

        extension NSDate {
            convenience init(utcDate:String, dateFormat:String="yyyy-MM-dd HH:mm:ss.SSS+00:00") {
                // 2016-06-06 00:24:21.164493+00:00
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = dateFormat
                dateFormatter.timeZone = NSTimeZone(name: "UTC")
        
                let date = dateFormatter.dateFromString(utcDate)!
                let s = NSTimeZone.localTimeZone().secondsFromGMTForDate(date)
                let timeInterval = NSTimeInterval(s)
        
                self.init(timeInterval: timeInterval, sinceDate:date)
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-14
          • 2021-09-30
          • 2016-09-15
          • 1970-01-01
          相关资源
          最近更新 更多