问题
I've got an API I'm hitting that returns a date that's at midnight on the East Coast of the U.S. That date, in turn, is used by a computed var to return a localized string. The issue I'm encountering is anyone who's one or more time zones behind the Eastern time will get the day prior from the date object returned from the API.
Here's what I've come up with to address this. It feels hacky, so I was hoping to see if there's a better way to get a date object in the non-Eastern time zone that matches the month, day, and year of the original date object.
if let timeZone = TimeZone(identifier: "America/New_York"),
let date = dateObjectFromTheAPI {
var dateComponentsFromAPI = Calendar.current.dateComponents(in: timeZone, from: date)
let easternYear = dateComponentsFromAPI.year
let easternMonth = dateComponentsFromAPI.month
let easternDay = dateComponentsFromAPI.day
if let year = easternYear,
let month = easternMonth,
let day = easternDay {
var dateWithTimeZoneStripped = DateComponents()
dateWithTimeZoneStripped.month = month
dateWithTimeZoneStripped.year = year
dateWithTimeZoneStripped.day = day
Calendar.current.date(from: dateWithTimeZoneStripped)
}
}
Thanks for reading.
来源:https://stackoverflow.com/questions/55548905/adjusting-a-date-from-an-api