Adjusting a date from an API

不羁的心 提交于 2019-12-13 04:22:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!