iosswiftnsdateformatternstimezone

Issue in formatting date string Swift 3


I need to convert the following date string in to a Date in Swift 3.

Fri Dec 09 16:18:43 AMST 2016

Here is the code that i have been using, but it's getting cash on this particular date string conversion. (This date was logged on Android using new Date().toString() method.)

static func formatDate(date: String) -> String {
        let dateFormatter = DateFormatter()

        dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy" 
        //Works for "Fri Sep 16 10:55:48 GMT+05:30 2016"

        var myDate = dateFormatter.date(from: date)
        // My date returns nil on "Fri Dec 09 16:18:43 AMST 2016"

        dateFormatter.dateFormat = "dd/MM/yyyy"
        return "\(dateFormatter.string(from: myDate!))"
    }

There are both type of strings in the database. I tried with various types of Timezone formats (z/zz/zzz/zzzz/zzzzz) but always myDate returns nil.

Any help would be appreciated. Thanks In Advance.


Solution

  • Apple doc for TimeZone(abbreviation:):

    In general, you are discouraged from using abbreviations except for unique instances such as “GMT”. Time Zone abbreviations are not standardized and so a given abbreviation may have multiple meanings.

    Does AMST represents "Amazon Summer Time" (UTC-3) or "Armenia Summer Time" (UTC+5)? See: https://www.timeanddate.com/time/zones

    That's probably why it can't detect the proper timezone to use.

    Solutions I can propose:

    1. If you know which timezone AMST is:
      • replace AMST by UTC-3 or UTC+5 in the date string
      • remove AMST from the date string and use dateFormatter.timeZone = TimeZone(secondsFromGMT: -3 or 5 * 3600)
    2. Have your source output a more precise timezone.

    Note the following code, where AMST is understood correctly:

    let df = DateFormatter()
    df.locale = Locale.init(identifier: "pt_BR") // assuming AMST is Amazon Summer Time (UTC -3)
    df.dateFormat = "HH:mm:ss z"
    
    print(df.date(from: "16:18:43 AMST")) // Optional(2000-01-01 19:18:43 +0000)
    

    But as soon as you include English day or month names (e.g. Fri or Dec) it will produce nil (because they aren't in Portuguese).