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

后端 未结 7 1186
一生所求
一生所求 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!!

    0 讨论(0)
  • 2020-12-02 08:50

    By the help of Mrugesh Tank Answer,

    I have updated his answer and creating the extensions for the date. So that you can easily access the functions from anywhere either from ViewController or either from cell class as well.

    extension String {
    
      //MARK:- Convert UTC To Local Date by passing date formats value
      func UTCToLocal(incomingFormat: String, outGoingFormat: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = incomingFormat
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
        let dt = dateFormatter.date(from: self)
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = outGoingFormat
    
        return dateFormatter.string(from: dt ?? Date())
      }
    
      //MARK:- Convert Local To UTC Date by passing date formats value
      func localToUTC(incomingFormat: String, outGoingFormat: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = incomingFormat
        dateFormatter.calendar = NSCalendar.current
        dateFormatter.timeZone = TimeZone.current
    
        let dt = dateFormatter.date(from: self)
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        dateFormatter.dateFormat = outGoingFormat
    
        return dateFormatter.string(from: dt ?? Date())
      }
    }
    

    Example how to use it:-

    Note:- eventStartDate is the string which you have to converted in your format like this:- "2018-07-11T16:22:00.000Z" 
    
    let finalDate = eventStartDate.UTCToLocal(incomingFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ", outGoingFormat: "MMM d, yyyy h:mm a")
    
    0 讨论(0)
  • 2020-12-02 08:56

    You can use in swift 4/5

      var myDate:String = "2020-02-18 14:30:57"
        var convertedLocalTime:String = ""
    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
        if let dt = dateFormatter.date(from: myDate) {
            dateFormatter.timeZone = TimeZone.current
            dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
            convertedLocalTime = dateFormatter.string(from: dt)
        } else {
            print("There was an error decoding the string")
        }
    
        print("convertedLocalTime--",convertedLocalTime)
    
    0 讨论(0)
  • 2020-12-02 08:57

    For everyone using TimeZone objects. I would advise you to create your TimeZone from identifier rather than abbreviation when you have the possibility.

    This prevents errors caused by daylight saving.

    To illustrate my point let's take an example. You can instantiate like this let timeZone = TimeZone(identifier: "Europe/Paris") or like that let timeZone = TimeZone(abbreviation: "CEST") or "UTC +2:00"

    But this is time zone for summer CEST meaning Central Europe Summer Time We have CET meaning Central Europe Time for winter which is "UTC +1:00"

    You could manage daylight saving by your own with Date.isDaylightSavingsTime but this means more code and you don't have control on where your daylight saving sprang from. "indicates whether the receiver is currently using daylight saving time" from official doc

    All is that is to say favour TimeZone(identifier: ...)

    0 讨论(0)
  • 2020-12-02 08:59

    Please try it:

    func convertUTCToLocal(timeString: String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"
    
        dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
        let timeUTC = dateFormatter.date(from: timeString)
    
        if timeUTC != nil {
            dateFormatter.timeZone = NSTimeZone.local
    
            let localTime = dateFormatter.string(from: timeUTC!)
            return localTime
        }
    
        return nil
    }
    
    
    
    func convertLocalToUTC(localTime: String) -> String? {
    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"
        dateFormatter.timeZone = NSTimeZone.local
        let timeLocal = dateFormatter.date(from: localTime)
    
        if timeLocal != nil {
            dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
    
            let timeUTC = dateFormatter.string(from: timeLocal!)
            return timeUTC
        }
        return nil
    }
    
    
        var isTimeFromServer = true
        var time:String!
        var period:String!
        let timeString = "6:59 AM" //Current UTC time
    
    
        if isTimeFromServer {
            print(convertUTCToLocal(timeString: timeString))
        } else {
            print(convertLocalToUTC(localTime: timeString))
        }
    
    0 讨论(0)
  • 2020-12-02 09:03

    If you need to convert timestamp you can use timezoneOffset like here:

    if let dateStr = model.date, let dateInt = Int(dateStr) {
                let timezoneOffset =  TimeZone.current.secondsFromGMT()
                let localDateInt = dateInt + timezoneOffset
                let date = Date(timeIntervalSince1970: Double(localDateInt))
                cell.dateLbl.text = date.toShortDateTimeString()
            }
    
    0 讨论(0)
提交回复
热议问题