Iniamudhan
Iniamudhan

Reputation: 508

Swift DateFormatter - Parse from UTC String

I'm using a String extension to parse utc string to Date. But the parsed date is wrong. Not sure what i'm missing.

extension String {
var parseUTCDateTime:Date? {
    let parser = DateFormatter()
    parser.dateFormat = "MM/dd/yyyy HH:mm:ss a"
    if let result = parser.date(from: self) {
       return result
    }
    return nil
}

When I do "3/7/2022 7:40:17 AM".parseUTCDateTime, the result returned 2022-03-06 19:10:17 UTC.

Ideally the result should be 2022-03-06 07:10:17 UTC as the string contains AM in it.

Upvotes: 0

Views: 159

Answers (1)

user652038
user652038

Reputation:

Format strings have type-safe interpolation now, so you don't need to worry about the hh vs HH anymore that tripped you up.

try Date(utc: "3/7/2022 7:40:17 AM")
extension Date {
  init(utc string: ParseStrategy.ParseInput) throws {
    try self.init(
      string,
      strategy: ParseStrategy(
        format: """
          \(month: .defaultDigits)\
          /\(day: .defaultDigits)\
          /\(year: .defaultDigits)

          \(hour: .defaultDigits(clock: .twelveHour, hourCycle: .oneBased))\
          :\(minute: .defaultDigits)\
          :\(second: .defaultDigits)

          \(dayPeriod: .standard(.narrow))
          """,
        timeZone: .init(abbreviation: "UTC")!,
        isLenient: false
      )
    )
  }
}

Upvotes: 2

Related Questions