Swift Date Timezone Issue

杀马特。学长 韩版系。学妹 提交于 2019-12-07 17:18:51

问题


extension Formatter {
    static let iso8601: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.timeZone = TimeZone.init(identifier: "America/New_York")
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        return formatter
    }()
}
extension Date {
    var iso8601: String {
        return Formatter.iso8601.string(from: self)
    }
}

extension String {
    var dateFromISO8601: Date? {
        return Formatter.iso8601.date(from: self)   // "Mar 22, 2017, 10:22 AM"
    }
}



let dateFormat:String = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let strDate: String = "2017-10-09T00:00:00.966Z"
if let dateFromString = strDate.dateFromISO8601
{
    print(dateFromString.iso8601)
}

Ok, so it does not do anything with the dateFormatter.date(from: sweDate)!) then? How can I get the string value to Date?

As per my knowledge Date doesn't store the time zone so it always prints the UTC time no matter what the time zone i have used upon formatting.

So what is the solution as i have to compare my local date with the converted date. which i cannot compare with the string. Any help is appreciated.


回答1:


You should use Calendar method dateComponents(in: TimeZone) to check the relative date components in a different time zone as follow:

let dateString = "2017-10-09T18:00:00.000Z"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
let date = formatter.date(from: dateString)!  // "Oct 9, 2017 at 3:00 PM" in Brazil
                                              // "Oct 9, 2017 at 2:00 PM" in New York
let components = Calendar.current.dateComponents(in: TimeZone(identifier: "America/New_York")!, from: date)  //calendar: gregorian (fixed) timeZone: America/New_York (fixed) era: 1 year: 2017 month: 10 day: 9 hour: 14 minute: 0 second: 0 nanosecond: 0 weekday: 2 weekdayOrdinal: 2 quarter: 0 weekOfMonth: 2 weekOfYear: 41 yearForWeekOfYear: 2017 isLeapMonth: false

if 8..<16 ~= components.hour!  {
    print("store is open in NY").  // "store is open in NY\n"
}


来源:https://stackoverflow.com/questions/46659148/swift-date-timezone-issue

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