Error in NSDateFormatter

1

I have a small error in NSDateFormatter() . When I start the application, it loads it and shows me the date, but when I change the month and go through the function again, it gives me an error.

func supplementaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
       let dateformatter = NSDateFormatter()
        dateformatter.dateFormat = "yyyy-MM-dd"
        let date2 = dateformatter.stringFromDate(dayView.date.convertedDate()!)

        let date_Array = ["2016-02-10","2016-02-11","2016-02-12","2016-01-11"]     
        for(var i=0;i<date_Array.count;i++)
        {
            if(date2==date_Array[i])
            {
                return true
            }
        return false
    }

The problem is in dateformatter.stringFromDate(dayView.date.convertedDate()!) Since you are converting to a String.

The error is fixed. The problem comes from the dayView since you have to specify the Day, Month and year. I leave the code fixed.

func supplementaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
        let dateformatter = NSDateFormatter()
        dateformatter.dateFormat = "yyyy-MM-dd"
        let date_Array = [[2016,02,10],[2016,02,11],[2016,02,12],[2016,01,11]]
        for(var i=0;i<date_Array.count;i++)
        {
        if let date = dayView.date {
            if(date.day == date_Array[i][2] && date.month == date_Array[i][1] && date.year == date_Array[i][0]) {
                return true
            }
        } else {

        }
    }
        return false
    }

What we do is specify the day, month and year and the error does not come out anymore, because when it goes through the for if it will no longer give an error.

    
asked by Bogdan 14.02.2016 в 12:45
source

1 answer

0

Probably the problem is that dayView.date.convertedDate() is nil, since it is a Optional and you have not verified if it exists before using it. You could modify the code in the following way:

func supplementaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
    let dateformatter = NSDateFormatter()
    dateformatter.dateFormat = "yyyy-MM-dd"
    guard let converted = dayView.date.convertedDate() else {
        return false
    }
    let date2 = dateformatter.stringFromDate(converted)

    let date_Array = ["2016-02-10","2016-02-11","2016-02-12","2016-01-11"]
    let date_Array2 = ["2016-02-20","2016-02-21","2016-02-22","2016-01-22"]


    for(var i=0;i<date_Array.count;i++)
    {
        if(date2==date_Array[i])
        {
            color = UIColor.yellowColor().CGColor
            return true
        }

        if(date2==date_Array2[i])
        {
            color = UIColor.blackColor().CGColor
            return true
        }

    }
    return false
  }
}

In this way, if dayView.date.convertedDate() exists it will continue without problem, otherwise it will return false and the function will not continue.

    
answered by 14.02.2016 в 17:54