如何将UTC时间转换为本地时间在Swift 3中?

时间:2018-03-07 04:50:16

标签: swift

在这里,我想将UTC时间转换为swift 3中的本地时间格式,但我无法转换它。请帮我这个

let StrDate = "2018-03-06T13:32:57 +05:30"我想将此日期转换为本地时间格式。

 func convertStringDateFormateUTC(strDate: String,
     strCurrentFormateType:String, strFormateType:String) -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = strCurrentFormateType
            var strNewdate = NSDate()
            strNewdate = dateFormatter.date(from: strDate)! as NSDate
            dateFormatter.dateFormat = strFormateType;
            dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
            return dateFormatter.string(from: strNewdate as Date)
        }

1 个答案:

答案 0 :(得分:0)

使用TimeZone.current检测本地时区并应用它。

let formatter = DateFormatter()
// initially set the format based on your datepicker date
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
//print(localTimeZoneAbbreviation)
formatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)
// convert your string to date
let yourDate = formatter.date(from: strDate)
//then again set the date format which type of output you need

在你的功能中:

func convertStringDateFormateUTC(strDate: String,
                                 strCurrentFormateType:String, strFormateType:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = strCurrentFormateType

    var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
    dateFormatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)

    var strNewdate = NSDate()
    strNewdate = dateFormatter.date(from: strDate)! as NSDate
    dateFormatter.dateFormat = strFormateType;
    dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
    return dateFormatter.string(from: strNewdate as Date)
}
相关问题