4
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)
}

好的,所以它对 dateFormatter.date(from: sweDate)!) 没有任何作用呢?如何将字符串值获取到日期?

据我所知,日期不存储时区,因此无论我在格式化时使用什么时区,它总是打印 UTC 时间。

那么解决方案是什么,因为我必须将我的本地日期与转换后的日期进行比较。我无法与字符串进行比较。任何帮助表示赞赏。

4

1 回答 1

4

您应该使用 Calendar 方法dateComponents(in: TimeZone)检查不同时区中的相对日期组件,如下所示:

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"
}
于 2017-10-10T06:46:05.163 回答