【问题标题】:IOS conversion of UTC to local time not accurateIOS将UTC转换为本地时间不准确
【发布时间】:2018-09-13 11:54:39
【问题描述】:

我正在尝试在 Swift 4 中将 UTC 转换为设备本地时间。我在 stackoverflow 上找到了许多解决方案,并在我的代码中实现了它们。我的代码运行良好,但没有返回正确的答案。

我的代码是:

func UTCToLocal() -> String {
    let a = "2:36:27 PM"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm:ss aa"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    let dt = dateFormatter.date(from: a)
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.defaultDate = Date()
    dateFormatter.dateFormat = "hh:mm:ss aa"

    return dateFormatter.string(from: dt!)
}

根据我的当地时间,黎巴嫩,此方法应返回值 5:36:27 PM。但是,它会在下午 4:36:27 返回。

注意:我检查了设备的本地时间并且设置正确

【问题讨论】:

  • 你在夏天吗?
  • isDaylightSavingTime of DateFormatter() 是你的朋友
  • @MartinR 我不认为它是重复的。 Carpsen90的解决方案解决了这个问题,和你发布的问题不同。
  • @SinanNoureddine: 完全相同的问题,正确设置dateFormatter.defaultDate 确实可以解决它。 Carpsen90 提出了不同的解决方案(我对此仍有一些疑问)。

标签: ios swift utc


【解决方案1】:

这是由于黎巴嫩的Daylight Saving Time。您可以通过在您的时区使用daylightSavingTimeOffset(for:) 方法来考虑时间偏移:

func UTCToLocal() -> String {
    let a = "2:36:27 PM"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm:ss aa"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    let dt = dateFormatter.date(from: a)

    dateFormatter.timeZone = TimeZone.current
    let offset = dateFormatter.timeZone.daylightSavingTimeOffset(for: dt!)
    dateFormatter.defaultDate = Date()
    dateFormatter.dateFormat = "hh:mm:ss aa"
    return dateFormatter.string(from: dt! + offset)
}

UTCToLocal()

请注意,dt 是“2000 年 1 月 1 日下午 2:36”,因为您尚未在 a 中指定 .day.month.year 日期组件

【讨论】:

  • 谢谢!这是解决方案
  • 除非我弄错了,否则在调整时钟的日子(从/到 DST)这可能会给出错误的结果。 daylightSavingTimeOffset() 给出“现在”的日光偏移,而不是要转换的时间。
猜你喜欢
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 2018-07-27
  • 2010-11-19
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多