Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ISO8601DateFormatter treats timeZone differently from DateFormatter #877

Open
adam-fowler opened this issue Aug 20, 2024 · 1 comment
Open

Comments

@adam-fowler
Copy link

When parsing a date with DateFormatter is you set the timeZone of the DateFormatter then the parsed date will be in that time zone. When parsing a date with ISO8601DateFormatter the timeZone parameter is ignored and the Date is always assumed to be UTC.

The output from the following code is

2021-06-21 20:10:15 +0000
2021-06-21 21:10:15 +0000
import Foundation

// create date formatter to parse ISO8601 date strings
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 3600)!

let date = dateFormatter.date(from: "2021-06-21T21:10:15Z")
print(date!)

let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.timeZone = TimeZone(secondsFromGMT: 3600)!

let date2 = iso8601DateFormatter.date(from: "2021-06-21T21:10:15Z")
print(date2!)
@prachigauriar
Copy link

I believe the issue here is that you’re using a literal Z in your DateFormatter’s dateFormat. In ISO-8601, the Z indicates UTC. If you update your DateFormatter to be "yyyy-MM-dd'T'HH:mm:ssZZZZZ", both will give the same result:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 3600)!

let date = dateFormatter.date(from: "2021-06-21T21:10:15Z")
print(date!)


let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.timeZone = TimeZone(secondsFromGMT: 3600)!

let date2 = iso8601DateFormatter.date(from: "2021-06-21T21:10:15Z")
print(date2!)

Output:

2021-06-21 21:10:15 +0000
2021-06-21 21:10:15 +0000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants