NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

DateFormatter intermittent error - "Date string does not match format expected by formatter"

Forums > SwiftUI

Hello everyone.!

I was practicing decoding dates from .json files, and came across a very bizarre problem.

Below are my decode file and my main view file. (These are pretty identical to what we've learned in Moonshot project)

Bundle-Codable.swift

extension Bundle {

    func decode<T: Codable> (_ file: String) -> T {

        // Find path to the file
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Failed to locate \(file) in bundle.")
        }
        // load information of the url into data
        guard let data = try? Data(contentsOf: url) else {
            fatalError("Failed to load \(file) from bundle")
        }

        let decoder = JSONDecoder()

        // Decoding "Date" format
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        decoder.dateDecodingStrategy = .formatted(formatter)

        do {
            let loaded = try decoder.decode(T.self, from: data)
            return loaded
        } catch {
            fatalError("Failed to decode \(file) from bundle. Error: \(error)")
        }
    }
}

ContentView.swift

struct Model: Codable, Identifiable {
    let id = UUID()
    let date: Date?

    var formattedLaunchDate: String {
        date?.formatted(date: .abbreviated, time: .omitted) ?? "N/A"
    }
}

let dates: [Model] = Bundle.main.decode("sample1.json")

struct ContentView: View {
    var body: some View {
        VStack {
            ForEach (dates) { date in
                    Text(date.formattedLaunchDate)
            }
        }
    }
}

Now here's where it get's interesting. I have two almost identical json files; one works perefectly fine but the other one throws an error.

sample1.json (WORKS)

[
    {
        "date": "1951-05-04"
    },
    {
        "date": "1951-05-07"
    },
    {
        "date": "1951-05-08"
    }
]

sample2.json (ERROR)

[
    {
        "date": "1951-05-04"
    },
    {
        "date": "1951-05-06"
    },
    {
        "date": "1951-05-07"
    },
    {
        "date": "1951-05-08"
    }
]

As you can see, the only difference between sample1 and sample2 is the addition of "date": "1951-05-06". And naturally, that (index: 1) is where the error occurs.

Error: dataCorrupted(Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "date", intValue: nil)], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil)).

It seems like from a json file with thousands of dates, this happens with around 1 out of 1000 dates. Any thoughts on why this might happen?

   

Not sure about the error, but it seems you have an extra comma in the first sample just before the closing ]

   

@Icemonster13 - Oh yeah, thank you. But that shouldn't (and doesn't) change much.. still getting the same error.

   

I cannot reproduce that error with the data samples provided here. You say it happens on about 1 out of 1000; can you upload a sample file of that size to github or something so we can test it?

   

@roosterboy - That's interesting. I wonder if it has to do with date settings on different devices.

Here's a github link to the sample project, with sample1.json (working), sample2.json (error), and original.json (error). https://github.com/lululucaschae/DateConverter

In the original file, the error happens at the 125th index ("1951-05-06"). When I skip that element and run it agian, the error then occurs at the 1584th index (hence why I said it roughly happen around 1 out of 1000 dates.) I've attached these errors on github. https://github.com/lululucaschae/DateConverter/issues/1

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.