【问题标题】:How to convert date from one format to another? Need to get date to "Tue Apr 3 22:10:06 2018" format如何将日期从一种格式转换为另一种格式?需要将日期设为“Tue Apr 3 22:10:06 2018”格式
【发布时间】:2018-05-10 01:16:39
【问题描述】:

如何将“2018-04-03 22:10:06”转换为“Tue Apr 3 22:10:06 2018”?显然不是那些具体的日期,而是那种格式。

我找到了这个解决方案:

How to convert date format from dd/MM/YYYY to YYYY-MM-dd in swift

但我无法得到准确的格式。

【问题讨论】:

  • yyyy-MM-dd HH:mm:ss 似乎在输入中,E MMM d HH:mm:ss yyyy 似乎是输出(引用自 nsdateformatter.com
  • 你知道你的日期字符串时区是什么吗?

标签: swift


【解决方案1】:

所以,我只是把它扔进了游乐场

let inFormat = DateFormatter()
inFormat.dateFormat = "yyyy-MM-dd HH:mm:ss"

let date = inFormat.date(from: "2018-04-03 22:10:06")

let outFormat = DateFormatter()
outFormat.dateFormat = "E MMM d HH:mm:ss yyyy"
outFormat.string(from: date!)

最终输出Tue Apr 3 22:10:06 2018

格式最初引用自nsdateformatter.com

当然,这将使用当前系统 TimeZoneLocale,因此您可能需要对此进行更多调查

【讨论】:

  • 注意,解析固定日期格式时需要将locale设置为en_US_POSIX
  • @LeoDabus 你能解释一下为什么吗?我没有问题,只是想了解更多
  • 否则会受到设备区域和用户设置的影响,如果设备设置为12小时(上午/下午格式)可能会崩溃
  • @LeoDabus 啊,点 - 我确实在最后“间接”添加了这一点
  • 顺便说一句,通常在解析日期字符串时,您应该使用 UTC 时区而不是当前时区
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
相关资源
最近更新 更多