Search code examples
iosswiftdatensdateformatter

Get the format of date | Swift | iOS


As per the requirement, my API might return date in either "2018-01-01" or "01-01-2018" or "2018-01-01T00:00:00" format

How can I check the format of the date?

eg: my code for API response "2018-01-01" should return me "yyyy-MM-dd" etc..

I can do this by checking length of my characters and by assigning date format accordingly..but i feel this is not the right approach.


Solution

  • You just need to define your date formats and try each of them. One of them will succeed. Just make sure all your date strings are from the same timezone (I suppose they are all UTC) and don't forget to set the date formatter locale to "en_US_POSIX" when working with fixed format dates:

    let dateStrings = ["2018-01-01", "01-01-2018", "2018-01-01T00:00:00"]
    let dateFormats = ["yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd", "MM-dd-yyyy"]
    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: .iso8601)
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.timeZone = TimeZone(secondsFromGMT: 0)
    var dates: [Date] = []
    for dateString in dateStrings {
        for dateFormat in dateFormats {
            formatter.dateFormat = dateFormat
            if let date = formatter.date(from: dateString) {
                dates.append(date)
                print("dateFormat:", dateFormat)
                print("date:", date)
                break
            }
        }
    }
    

    This will print

    dateFormat: yyyy-MM-dd

    date: 2018-01-01 00:00:00 +0000

    dateFormat: MM-dd-yyyy

    date: 2018-01-01 00:00:00 +0000

    dateFormat: yyyy-MM-dd'T'HH:mm:ss

    date: 2018-01-01 00:00:00 +0000