【问题标题】:Getting the timezone (GMT) in Swift在 Swift 中获取时区 (GMT)
【发布时间】:2019-04-06 10:02:11
【问题描述】:

我有一个显示不同国家时区的应用程序。目前代码如下所示:

if indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 6 || indexPath.row == 7{
    cell.aseanDate.text = dayFormatter.string(from: Date() as Date)
    cell.aseanTime.text = dateFormatter2.string(from: Date() as Date)
    cell.aseanTime.textAlignment = .center
    cell.aseanTimeZone.text = "\(TimeZone(abbreviation: "UTC+07")!)"
}

时间本身显示正确,但在aseanTimezone.text 下显示GMT +0800(固定)

是否可以更改它以显示 GMT 但没有第一个零和单词(固定)?

【问题讨论】:

  • 如果您对时区进行硬编码,那么为什么还要创建TimeZone 实例呢?只需输入您想要的特定字符串即可。
  • 不相关但Date() as Date 毫无意义。只需使用Date()。无需将 Date 转换为 Date

标签: ios swift timezone


【解决方案1】:

我想你正在寻找这种方法

localizedName(for style: NSTimeZone.NameStyle, locale: Locale?)

但是,它也会删除尾随零GMT+7

TimeZone(abbreviation: "UTC+07")!.localizedName(for: .shortStandard, locale: nil)! // => GMT+7

其他可用选项

.standard
.shortStandard
.daylightSaving
.shortDaylightSaving
.generic
.shortGeneric

【讨论】:

    【解决方案2】:

    试试下面的代码

    if indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 6 || indexPath.row == 7 {
        let newDate = Date()
        formatter.dateStyle = .none
        formatter.timeStyle = .short
        formatter.dateFormat = "hh:mm a"
        formatter.timeZone = TimeZone(identifier:"Your timezoon string here!!")
        cell.aseanTimeZone.text = = formatter.string(from: newDate)
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多