gpt4 book ai didi

Swift 日期时区问题

转载 作者:搜寻专家 更新时间:2023-11-01 07:08:22 27 4
gpt4 key购买 nike

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 的字符串值?

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

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

最佳答案

您应该使用 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"
}

关于Swift 日期时区问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46659148/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com