Skip to content

Instantly share code, notes, and snippets.

@raunakp
Created August 1, 2019 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raunakp/6dff54a3bcc17c76a92d77735c8680d4 to your computer and use it in GitHub Desktop.
Save raunakp/6dff54a3bcc17c76a92d77735c8680d4 to your computer and use it in GitHub Desktop.
import Foundation
// Create TimeZone instance from UTC offset string like "-07:30"
extension TimeZone {
private static let refZoneString = "+0000"
private static var _offsetTimezoneDateFormatter: DateFormatter!
static var offsetTimezoneDateFormatter: DateFormatter {
if let _offsetTimezoneDateFormatter = _offsetTimezoneDateFormatter {
return _offsetTimezoneDateFormatter
}
_offsetTimezoneDateFormatter = DateFormatter()
_offsetTimezoneDateFormatter.dateFormat = "Z"
return _offsetTimezoneDateFormatter
}
private static let refUTCDate = offsetTimezoneDateFormatter.date(from: refZoneString)
init?(UTCOffsetString ofs: String) {
guard let refDate = TimeZone.refUTCDate,
let date = TimeZone.offsetTimezoneDateFormatter.date(from: ofs) else {
return nil
}
if let offsetInSec = Calendar.current.dateComponents([.second], from: date, to: refDate).second {
self.init(secondsFromGMT: offsetInSec)
} else {
return nil
}
}
}
let tz = TimeZone.init(UTCOffsetString: "-07:30")
print(tz?.identifier ?? "unknown")
// Prints GMT-0730
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment