Search code examples
iosswiftiphonexcodedateformatter

Swift 5 - Unexplainable DateFormatter Crash


My app uses a timer which is constructed using a string in the MM-dd-yyyy h:mm a format. When the user surpasses the time noted by the resetTimeString, the next reset time is determined by incrementing to the next day (the 'a' value doesn't change) and storing the value in the database. Simply put, it represents a daily timer and each user is able to choose their own 'a' value.

I had a number of users reach out concerning a crash and after comparing their values in the database, it appears they all had a resetTimeString of 03-14-2021 2:00 AM

    var resetTime: Date?
    let resetTimeFormatter = DateFormatter()

    resetTimeFormatter.dateFormat = "MM-dd-yyyy h:mm a"
    
    if let resetString = resetTimeString { //value in DB
        resetTime = resetTimeFormatter.date(from: resetString)! // <- Only crashes with 03-14-2021 2:00 AM 
    }

I tested a range of different values for the resetTimeString value, and they all work perfectly fine:

03-13-2021 2:00 AM

03-14-2021 1:00 AM

03-14-2021 3:00 AM

03-15-2021 2:00 AM

I am very confused about this crash and thought I would seek some assistance; any help is appreciated!


Solution

  • In your locale the daylight saving time changes at 2 am on March 14, 2021, therefore the particular date doesn't exist.