0

I'm trying to convert a date-time string to a date, with a DateFormatter with the TimeZone set to UTC.

The input string is in the format yyyy-MM-dd'T'HH:mm:ss'Z'.

For some reason, the subsequent Date produced is in UTC - 1:00:00. For example a date-time string of "2023-04-28T12:18:15Z" is producing a Date of 2023-04-28 11:18:15 UTC.

    let inputLogDateFormatter: DateFormatter = DateFormatter()
    private init() {
        self.inputLogDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        self.inputDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        self.inputDateFormatter.locale = Locale(identifier: "en_US_POSIX")
    }
......
let logDateTime: String = // LogString in 'inputLogDate' format.
let date: Date = self.inputLogDateFormatter.date(from: logDateTime) ?? Date(timeIntervalSince1970: 0) // Produces a time - 1 hour from input time string.
6
  • Check your init, you are configuring some other date formatter object in the last two lines. Commented Apr 28, 2023 at 15:00
  • The Z in the string represents the timezone. Don't ignore it. Do not quote the Z in the format and then there is no need to set a timezone on the formatter. Commented Apr 28, 2023 at 16:16
  • @JoakimDanielson Yes, you're completely right. Definitely a facepalm moment! Thank you! Commented Apr 28, 2023 at 16:59
  • 1
    What is the reason not to use ISO8601DateFormatter? Commented Apr 28, 2023 at 17:09
  • @vadian The input string isn't in the format yyyy-MM-dd HH:mm:ss.SSS? Commented Apr 29, 2023 at 22:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.