简体   繁体   English

快速日期时区问题

[英]Swift Date Timezone Issue

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? 好的,那么它对dateFormatter.date(from:sweDate)!不做任何事情吗? How can I get the string value to Date? 如何将字符串值获取为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. 据我所知,日期不存储时区,因此无论我在格式化时使用的时区如何,它始终会打印UTC时间。

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. 任何帮助表示赞赏。

You should use Calendar method dateComponents(in: TimeZone) to check the relative date components in a different time zone as follow: 您应该使用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"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM