英文:
How to convert Go time to Swift Date?
问题
所以基本上我正在从我在Go中构建的虚拟API中获取用户列表,并将其传递到我的SwiftUI项目中。每个用户都有一个CreatedAt
字段,它的填充方式如下:
// user.models.go
user := User{Username: "Spongebob", Password: "Squarepants", CreatedAt: time.Now()}
我的问题是我想将CreatedAt字段转换为Swift日期,以便在前端中使用,但我似乎无法做到。我已经看过一些解决方案,但它们都打印出nil
。CreatedAt字段的样子如下:
{
...
"created_at": "2022-10-30T21:11:52.540958635-07:00"
...
}
我知道我可以在API响应之前将时间戳转换为Unix时间,但我更希望由前端来处理,因为我希望后端只专注于发送响应,而不是格式化响应。
谢谢!
英文:
So basically I am fetching a list of user from a dummy API I built in Go into my SwiftUI project. Each user has a CreatedAt
field which is populated like so:
// user.models.go
user := User{Username: "Spongebob", Password: "Squarepants", CreatedAt: time.Now()}
My problem is I want to convert the CreatedAt field into a Swift date so that I may use it in my frontend but I can't seem to get it. I have looked at a few solutions but they all print nil
. This is what the CreatedAt field looks like:
{
...
"created_at": "2022-10-30T21:11:52.540958635-07:00"
...
}
I know I can convert the timestamp into unix time in the API prior to the response but I'd rather have it so the frontend does this instead because I want the backend to simply focus on sending responses, not formatting them as well.
Thank you!
答案1
得分: 2
//2022-10-30T21:11:52.540958635-07:00
let dateString = "2022-10-30T21:11:52.540958635-07:00"
let dateFormatter = DateFormatter()
//dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSXXX"
let date = dateFormatter.date(from: dateString)
print(date!)
//2022-10-30T21:11:52.540958635-07:00
let dateString = "2022-10-30T21:11:52.540958635-07:00"
let dateFormatter = DateFormatter()
//dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSXXX"
let date = dateFormatter.date(from: dateString)
print(date!)
以上是要翻译的内容。
英文:
//2022-10-30T21:11:52.540958635-07:00
let dateString = "2022-10-30T21:11:52.540958635-07:00"
let dateFormatter = DateFormatter()
//dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSXXX"
let date = dateFormatter.date(from: dateString)
print(date!)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论