json - Swift json 时间值到本地时区

标签 json swift nstimezone

我有一个 json 请求可以产生两种不同类型的时间值。两种方式都是 UTC 时间,但我需要将其转换为本地时间。

2015-12-01T13:05:33+00:00

1:05:33 PM

我的尝试。

let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle //Set time style
dateFormatter.timeZone = NSTimeZone()
let localDate: NSDate? = dateFormatter.dateFromString(time1)
print(localDate)

这就是我得到的结果。 2000-01-01 19:05:33 +0000 如果我使用 1:05:18 PM 值。

获取json值的行。

let time1 = json["results"]["time1"].string!

最佳答案

好的,有几件事:

  1. 解析 RFC 3339/ISO 8601 字符串:

    let string = "2015-12-01T13:05:33+00:00"
    
    let rfc3339Formatter = NSDateFormatter()
    rfc3339Formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    rfc3339Formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    let date = rfc3339Formatter.dateFromString(string)
    

    请注意,我已经设置了语言环境(根据 Technical Q&A 1480 )。但是因为日期字符串包含时区信息,所以我可以使用 Z 格式化字符以便正确解释时区。

  2. 但是 NSDate 对象没有与它们关联的时区。事实上,如果我们执行在上一步中成功解析的 print(date),它将向我们显示 GMT/UTC 中的 NSDate,即使原始字符串是在不同的时区。

    只有当您使用格式化程序将此 NSDate 转换回要呈现给用户的新字符串时,时区才有意义。所以我们可以使用一个单独的格式化程序来创建输出字符串:

    let userDateFormatter = NSDateFormatter()
    userDateFormatter.dateStyle = .MediumStyle
    userDateFormatter.timeStyle = .MediumStyle
    let outputString = userDateFormatter.stringFromDate(date!)
    

    因为这没有指定时区,所以它会在用户的本地时区中创建一个字符串。并且因为我们没有覆盖 locale 并使用 .dateStyle.timeStyle,所以它会在创建时使用设备的当前本地化设置显示它要呈现给最终用户的字符串。

  3. 现在,如果您真的收到 UTC 时间(不包括时区?!哎呀,恕我直言,在 JSON 中看到它是一个非常糟糕的设计),那么您必须指定时区:

    let string = "1:05:33 PM"
    
    let utcTimeStringFormatter = NSDateFormatter()
    utcTimeStringFormatter.dateFormat = "hh:mm:ss a"
    utcTimeStringFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    let time = utcTimeStringFormatter.dateFromString(string)
    

    现在我们有了 time,一个 NSDate 包含了那个字符串表示的时间。但是同样,NSDate 对象本身没有时区。只有当我们将其转换回最终用户的字符串时,我们才能看到本地时区的时间:

    let userTimeFormatter = NSDateFormatter()
    userTimeFormatter.timeStyle = .MediumStyle
    let outputString = userTimeFormatter.stringFromDate(time!)
    

关于json - Swift json 时间值到本地时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34058167/

相关文章:

ios - 侧栏菜单的滑动手势无法正常工作 - Swift

ios - 如何在按钮中绘制文本

ios - GMT 与夏令时更改的本地时间转换

ios - 将 iOS 本地时区转换为已知时区

java - 尝试解析 JSON 数据时通过递归调用在 Android 中获取 StackOverFlowError

json - 在查询中选择特定列时如何将数组结果转换为 JSON 格式

ios - 绘制带阴影的渐变圆

objective-c - 如何在 iOS 中通过经纬度识别时区

java - 如何从表单检索 jsp web 项目中的 json obj 值

ruby-on-rails - 使用 Postman 和 Rails 时出现意外的 '<' 错误