ios 将 UTC 日期格式转换为本地 nsdate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29392874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:27:33  来源:igfitidea点击:

Converting UTC date format to local nsdate

iosswiftdatetimezonensdate

提问by ilan

I am getting from my server a string date in UTC time zone and I need to convert it to the local time zone.

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

MY CODE:

我的代码:

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

this prints -

这打印 -

utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 11:42:00 +0000)

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

if I remove

如果我删除

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

it prints

它打印

utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 08:42:00 +0000)

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

my local time zone is UTC +3 and in the first option I get UTC in the second option I get UTC -3

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

I should get

我应该得到

utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 14:42:00 +0000)

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

So how do I convert the UTC date format to local time?

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

回答by c_rath

Something along the following worked for me in Objective-C :

以下内容在 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];

I keep these two websites handy for converting different time formats: http://www.w3.org/TR/NOTE-datetime

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

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

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

In Swift it will be:

在 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!)

回答by Krunal

Try this Swift extension

试试这个 Swift 扩展

Swift 4: UTC/GMT ? Local (Current/System)

斯威夫特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

回答by TomazStoiljkovic

Swift version of c_rath answer:

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!)

回答by FredFlinstone

In Swift 3 this works well:

在 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!)

回答by Derek Hewitt

Expanding on what others have mentioned, here is a handy NSDateextension in Swift

扩展其他人提到的内容,这是NSDateSwift 中的一个方便的扩展

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
    }
}

回答by nidhin

I had to remove both z and milli seconds from c_rath solution. Works in swift 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)
    }
}

回答by Juan José Brown

Maybe you can try something like:

也许您可以尝试以下操作:

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)
    }
}