【问题标题】:Date Formatter in swiftswift中的日期格式化程序
【发布时间】:2018-10-03 06:46:59
【问题描述】:

我想获得这种类型的甲酸盐 -> 2018 年 4 月 20 日晚上 9:02:00 UTC+5:30 对于 Firestore 时间戳。我已经尝试过这段代码,但没有像上面那样得到正确的甲酸盐。

let date = Date()
let formatter = DateFormatter()

formatter.dateFormat = "MMMM d yyyy hh:mm:ss a Z"
formatter.timeZone = NSTimeZone(name: "IST") as TimeZone?

let result = formatter.string(from: date)
print(result)

已经使用这个格式化程序 formatter.dateFormat = "MMMM d yyyy'T'hh:mm:ss a Z"

谢谢

【问题讨论】:

  • "已经尝试过这段代码,但没有得到上述正确的甲酸盐。"它给了你什么?例如,我在您的格式中看不到 'at'
  • 确定需要在中间加上“at”吗?
  • 是的@AbhirajsinhThakore
  • @Rock 一个建议,将 timeStamp 保存为 unix 格式,如 this1524476327 并在客户端解析它以用于 UI 目的。
  • 不知道为什么每个dateFormat 的新问题有多种格式,因此每当需求更改时,您都会提出新问题。为什么不只用谷歌搜索那种特定的格式?

标签: ios swift dateformatter


【解决方案1】:

你可以这样使用:

    let date = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm:ss a 'UTC'Z" //If you dont want static "UTC" you can go for ZZZZ instead of 'UTC'Z.
    formatter.timeZone = TimeZone(abbreviation: "IST")
    let result1 = formatter.string(from: date)
    print(result1)

注意:如果不希望字符串中的UTC是静态的,也可以使用"MMMM dd, yyyy 'at' hh:mm:ss a ZZZZ"的格式

感谢Larme格式改进

输出:

【讨论】:

  • 有可能是 UTC+5:30 而不是 +0530 ?
  • 请检查编辑后的答案
  • formatter.dateFormat = "MMMM d, yyyy 'at' HH:mm:ss a Z" 无需合并即可完成相同的工作。
  • HH 而不是 hh 在之后的上午/下午很奇怪。
  • 感谢@Larme 的建议,
【解决方案2】:

喜欢

    let formatter = DateFormatter()
    //If you want it in your specific format you can simply add 'UTC'
    formatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm:ss a 'UTC'Z"
    formatter.timeZone = NSTimeZone(name: "IST") as TimeZone?
    let result = formatter.string(from: Date())
    print(result)

注意:如果要为字符串设置 currentTimezone,请使用格式 "MMMM dd, yyyy 'at' hh:mm:ss a ZZZZ"

你得到的输出为

【讨论】:

    【解决方案3】:

    如果您不想在小时中前导零,请尝试此操作,而小时是个位数。此外,您不需要将 NSTimeZone 类型转换为 TimeZone。您可以直接使用 TimeZone。

    let date = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM dd, yyyy 'at' h:mm:ss a 'UTC'Z"
    formatter.timeZone = TimeZone(abbreviation: "IST")
    let result = formatter.string(from: date)
    print(result)
    

    2018 年 4 月 23 日下午 3:09:01 UTC+0530

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多