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

后端 未结 7 1232
一生所求
一生所求 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 08:47

    I don't know what's wrong with your code.
    But looks too much unnecessary things are there like you're setting calendar, fetching some elements from string. Here is my small version of UTCToLocal and localToUTC function.
    But for that you need to pass string in specific format. Cause I've forcly unwrapped date objects. But you can use some guard conditions to prevent crashing your app.

    func localToUTC(dateStr: String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"
        dateFormatter.calendar = Calendar.current
        dateFormatter.timeZone = TimeZone.current
        
        if let date = dateFormatter.date(from: dateStr) {
            dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
            dateFormatter.dateFormat = "H:mm:ss"
        
            return dateFormatter.string(from: date)
        }
        return nil
    }
    
    func utcToLocal(dateStr: String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "H:mm:ss"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        
        if let date = dateFormatter.date(from: dateStr) {
            dateFormatter.timeZone = TimeZone.current
            dateFormatter.dateFormat = "h:mm a"
        
            return dateFormatter.string(from: date)
        }
        return nil
    }
    

    and call these function like below.

    print(utcToLocal(dateStr: "13:07:00"))
    print(localToUTC(dateStr: "06:40 PM"))
    

    Hope this will help you.
    Happy coding!!

提交回复
热议问题