iOS: Convert UTC NSDate to local Timezone

2019-01-01 08:37发布

How do I convert a UTC NSDate to local timezone NSDate in Objective C or/and Swift?

13条回答
爱死公子算了
2楼-- · 2019-01-01 09:11

Swift 3+: UTC to Local and Local to UTC

extension Date {

    // 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)
    }

    // 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)
    }
}
查看更多
登录 后发表回答