如何将日期字符串转换为时间字符串?
我有一个看起来像这样的字符串:
"date": "2022-06-30T02:15:00.000+07:00"
我格式化了它以将其转换为“ hh:mm”这样:
func formatTime(string: String) -> String {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
let date: Date? = dateFormatterGet.date(from: string)
return dateFormatterPrint.string(from: date ?? Date())
}
我希望它返回的结果为09:15,但它返回02:15。 有人可以告诉我我在哪里做错了吗?谢谢
I have a string that looks like this:
"date": "2022-06-30T02:15:00.000+07:00"
And I formatted it to convert to "HH:mm" like this:
func formatTime(string: String) -> String {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
let date: Date? = dateFormatterGet.date(from: string)
return dateFormatterPrint.string(from: date ?? Date())
}
The result I want it returns is 09:15, but it returns 02:15.
Can someone tell me where I went wrong? Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“ 2022-06-30T02:15:00.000+07:00”是时区的日期,距离UTC时区7小时。在UTC中的日期是“ 2022-06-29T19:15:00z”,
而DateFormatterPrint根据电话设置
需要设置UTC TimeZone的默认场所配置
"2022-06-30T02:15:00.000+07:00" is the date in the time zone plus 7 hours from the UTC time zone. Than this date in UTC is “ 2022-06-29T19:15:00Z”
while dateFormatterPrint has a default locale configuration according to the phone settings
You need to set UTC timezone
在这种情况下,您可能需要先将日期时间转换为当地时间:
转换为Localtime:
,然后:
结果:
希望这有助于您解决问题。
In this case you might want to convert the DateTime to your local time first:
Convert To LocalTime:
And then:
The Result:
I hope this help you solve your problem.