swift - 使用 DateFormatter 解析时正确的时间戳日期格式
问题描述
我有一个时间戳字符串,其形式为:
2018-03-06T06:28:39.887Z
并且需要将其格式化为更易于阅读的格式,我尝试了以下日期格式,但是日期无法解析
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "y-MM-ddTk:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2018-03-06T06:28:39.887Z")
我的日期格式缺少什么?
解决方案
Swift 3/4 的解决方案:
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26"){
print(dateFormatterPrint.string(from: date))
}
else {
print("There was an error decoding the string")
}
推荐阅读
- discord.js - DiscordJS 参数切片
- javascript - python/java 脚本:如何在 python 服务器上使用子协议?
- python-3.x - 在 Python 中 Ping
- visualization - Streamlit `altair_chart` 图表不是交互式的
- selenium-webdriver - 如何在 Cucumber-Java-TestNG 框架中处理 Extent Reports 的 createtest() 方法?
- github - 如果我将我的 github repo 转为私有,与之相关的云项目是否会遇到任何问题?
- javascript - (Canvas | Discord.js) 我正在尝试使用 `ctx.drawImage(background, 0, 0, canvas.width, canvas.height)` 设置背景,但该命令不起作用
- python - 在 Tornado 的阻塞上下文中调用异步函数
- android - 尝试运行 AVD 时“找不到 ADB” - 路径中的 adb.exe,重新安装了平台工具,并且没有安装防病毒软件
- javascript - 从源“null”访问 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制