快速日期时区问题 [英] 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)
}
好吧,那么它对dateFormatter.date(from:sweDate)!不做任何事情吗? 如何将字符串值获取为Date?
Ok, so it does not do anything with the dateFormatter.date(from: sweDate)!) then? How can I get the string value to Date?
据我所知,Date不存储时区,因此它始终打印UTC时间,无论我在格式化时使用了什么时区。
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.
推荐答案
您应使用Calendar方法 dateComponents(in:TimeZone )
来检查不同时区中的相对日期成分,如下所示:
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"
}
这篇关于快速日期时区问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!