Get current iPhone device timezone date and time from UTC-5 timezone date and time iPhone app?

前端 未结 3 1195
梦谈多话
梦谈多话 2020-11-30 20:20

In my iPhone application i am very struggling to convert the webservice response time to current device time. The webservice time in UTC-5 timezone. The app is

3条回答
  •  庸人自扰
    2020-11-30 20:43

    May this extension would be easier.

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

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

提交回复
热议问题