0

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.

7
  • In what timezone are you? Commented Mar 7, 2022 at 10:08
  • 3
    try using hh instead of HH. HH is for 24h method. Commented Mar 7, 2022 at 10:16
  • @burnsi I'm in IST timezone Commented Mar 7, 2022 at 11:04
  • 1
    @udi changing to hh returns - 2022-03-07 02:10:17 UTC Commented Mar 7, 2022 at 11:07
  • 1
    Set the time zone property of your formatter to UTC if that is what the input time is, by default it is using the current time zone of the device. Commented Mar 7, 2022 at 11:23

1 Answer 1

2

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
      )
    )
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.