Swift 3.0 : Convert server UTC time to local time and vice-versa

后端 未结 7 1189
一生所求
一生所求 2020-12-02 08:09

I want to convert server UTC time to local time and vice-versa. Here is my code..

var isTimeFromServer = true
var time:String!
var period:String!
let timeStr         


        
相关标签:
7条回答
  • 2020-12-02 09:12

    Mrugesh's answer is perfect, but if someone need to use their own formats, or in some different format, I've generalised it so you can give different format or same in both parameters.

    func localToUTC(date:String, fromFormat: String, toFormat: String) -> String {
    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = fromFormat
        dateFormatter.calendar = NSCalendar.current
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.date
        let dt = dateFormatter.date(from: date)
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        dateFormatter.dateFormat = toFormat
    
        return dateFormatter.string(from: dt!)
    }
    
    func UTCToLocal(date:String, fromFormat: String, toFormat: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = fromFormat
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
        let dt = dateFormatter.date(from: date)
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = toFormat
    
    return dateFormatter.string(from: dt!)
    }
    
    let localDateAsString = UTCToLocal(date: dateAsString!, fromFormat: "hh:mm a, dd MMM yyyy", toFormat: "hh:mm a, dd MMM yyyy")
    

    You can use it as above. Hope it helps.

    0 讨论(0)
提交回复
热议问题