Swift DateFormatter from String with (EEST)?

90 Views Asked by At

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.

3

There are 3 best solutions below

5
matt On BEST ANSWER

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)
2
soundflix On

For the dateFormat string you need to:

  • Escape all string content with '
  • Use 24h time format
  • Use time zone specific non-location field code "z" (equivalents are: zz, zzz, zzzz)
let dateString = "31-07-2023 12:44 (EEST)"

let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy' 'HH:mm' ('z')"

if let ptdate: Date = formatter.date(from: dateString) {
    print(ptdate)
}
2
Joakim Danielson On

"EEST" is a standard time zone abbreviation so you should use zzz and I also assume that the time format is 24h so configure the date formatter like this

formatter.dateFormat = "dd-MM-yyyy HH:mm (zzz)"

Update

Seems like a single z also works "dd-MM-yyyy HH:mm (z)"