Search code examples
swiftdatedateformatter

Swift DateFormatter from String with (EEST)?


i am trying to parse string date which is coming from an API to Date().

the date string is: 31-07-2023 12:44 (EEST)

My code:

let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy hh:mm (zzzz)" // "yyyy-MM-dd h:mm a"

if let ptdate = formatter.date(from: prayer.getString("time")) {
    // Not working!
}

i believe there is something missing in date format i am using which is dd-MM-yyyy hh:mm zzzz, i am not sure what it is, since i've spent hours googling date formats.


Solution

  • I did it like this (no date formatter needed):

    let dateString = "31-07-2023 12:44 (EEST)"
    let format: Date.FormatString = "\(day: .twoDigits)-\(month: .twoDigits)-\(year: .defaultDigits) \(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .oneBased)):\(minute: .twoDigits) (\(timeZone: .specificName(.short)))"
    var strategy = Date.ParseStrategy.fixed(format: format, timeZone: .current)
    let date = try? Date(dateString, strategy: strategy)