Search code examples
jsonswiftmacosdateformatter

SWIFT Inconsistent DateFormatter result


I am using a string extension function to convert a date string. The function is:

func convertDateString() -> String {
    let dateFormater = DateFormatter()
    var returnString = ""
    dateFormater.dateFormat = "yyyy-MM-dd'T'hh:mm:ss'Z'"    // Takes the format from the JSON journal entry for elite dangerous
    dateFormater.locale = Locale.current
    if let dateObj = dateFormater.date(from: self) {
    dateFormater.dateFormat = "dd MMM yyyy  hh:mm:ss"       // Converts it to a new string (as a date object)
        returnString = dateFormater.string(from: dateObj)   // Converts the date object back to a string
    } else {
        returnString = "Error converting date"
    }
    return returnString
}

I am using a data set which is an series of JSON objects calling the string extension to convert part of the result from the JSON reference file.

I am working on two machines - one a MACPRO and one a MacBookAir. Both are running the same version of MacOS (10.12.5) and the same version of Xcode.

When I run the app on the MACPRO it parses the JSON object file without an issue and converts each and every date correctly as expected in the function shown above. However, when I run the app on the MacBookAir, on exactly the same datafile, the JSON object file seems to be parsed without an issue however some (a few percent) of the dates do not convert as expected - they fail the if let dateObj = dateFormater.date(from: self) statement and are returned as "Error converting date".

I am at a loss to work out what is going on. I have tried removing the dateFormater.locale = Locale.current and it makes no difference.

The same JSON objects produce the error (i.e. each time I run the file it is the same JSON objects that produce the "Error converting date" response). When I look at the JSON object file in a text editor there appears to be no issues with the JSON object (I have also confirmed this in an online JSON object formatter and it reads the JSON object correctly.)

I should also add that I am using SwiftyJSON to parse the JSON objects.

Any help or suggestions gratefully received.

Is there a way to make my code more robust? Can anyone suggest why the different machine might make a difference given that the app the datafile, Xcode and MacOS are all the same.


Solution

  • My thanks to all who responded.

    After reading the article referenced by Code Different and focusing on the issue that David raised is added the following lines to my code:

        dateFormater.calendar = Calendar(identifier: .iso8601)
        dateFormater.locale = Locale(identifier: "en_US_POSIX")
        dateFormater.timeZone = TimeZone(secondsFromGMT: 0)
    

    in lieu of the 'dateFormater.locale = Locale.current' line. It now works perfectly and swaps between devices without a problem.