【问题标题】:swift How to convert time string +4:00 to Timezoneswift如何将时间字符串+4:00转换为时区
【发布时间】:2018-08-05 13:47:41
【问题描述】:

如何将字符串转换为时区?例如,我有字符串:

2016.9.5 - 16:36

这个时间是GMT+4,那么如何转换成时区呢?

【问题讨论】:

  • 您要转换到哪个时区?到目前为止,您尝试过什么?
  • 是的,您要转换到哪个时区?

标签: ios swift localization timezone timestamp


【解决方案1】:

首先从上面的字符串中删除'-' 然后将字符串传递给下面的方法

static func getDateFromString( _ str  : String) -> Date{
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
    dateFormatter.dateFormat = "yyyy.MM.dd HH:mm"
    return dateFormatter.date(from: str)!
}

【讨论】:

    【解决方案2】:

    如果您想将此字符串转换为 GMT 时间:

        let str = "2016.9.5 - 16:36"
    
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(secondsFromGMT:  4 * 60 * 60)
        dateFormatter.dateFormat = "yyyy.M.d - HH:mm"
        let date = dateFormatter.date(from: str)!
        print(date) // result : 2016-09-05 12:36:00 +0000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多