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!
CodePudding user response:
//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!)