从ISO8601日期字符串中提取时区

时间:2017-03-30 11:50:29

标签: regex swift datetime timezone nstimezone

我想从ISO8601日期字符串中提取时区,即2017-03-26T07:12:58-04:00。是否有内置的方法从ISO8601日期字符串或Swifty方式派生TimeZone来执行此操作?

以下是我到目前为止所获得的内容,但似乎很脆弱并且使用Objective-C类型。它将字符串的尾端转换为整数,然后偏离GMT:

func getTimeZone(iso8601 dateString: String) -> TimeZone? {
    guard !dateString.isEmpty else { return nil }

    let text = dateString as NSString
    let pattern = "[+|-]+\\d{2}:\\d{2}"
    let regex = try! NSRegularExpression(pattern: pattern)

    guard let result = regex.matches(in: text as String, range: NSRange(location: 0, length: text.length)).first else { return nil }

    let sub = text.substring(with: result.range)
    let start = dateString.index(dateString.startIndex, offsetBy: 1)
    let end = dateString.index(dateString.startIndex, offsetBy: 3)

    let startMin = dateString.index(dateString.startIndex, offsetBy: 4)
    let endMin = dateString.index(dateString.startIndex, offsetBy: 6)

    let offsetHour = Int(sub.substring(with: (start..<end))) ?? 0
    let offsetMin = Int(sub.substring(with: (startMin..<endMin))) ?? 0

    return sub[sub.startIndex] == "+"
        ? TimeZone(secondsFromGMT: offsetHour * 60 * 60 + offsetMin * 60)
        : TimeZone(secondsFromGMT: -offsetHour * 60 * 60 - offsetMin * 60)
}

有没有本地或更安全的方法来做到这一点?

0 个答案:

没有答案