NSDate - Convert Date to GMT

后端 未结 6 918
故里飘歌
故里飘歌 2020-11-28 02:45

I need the ability to convert an NSDate value to a GMT Date.

How can I go about converting an NSDate value to a GMT formatted NSDate<

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 03:31

    Swift 4:

    //UTC or GMT ⟺ Local 
    
    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)
        }
    
    }
    

提交回复
热议问题