Search code examples
iosswiftuitableviewnsdateformatter

How to convert date formate from 1999-05-18 to 18 may in uitable view swift


I have url of having dob's list with names and the response comes in this scenario "1993-03-28"....... along names and I have to show the date as 28 Mar I have created array of months and working but It printing all same dates for all members my code is

 var  dob = "\(arrdata[indexPath.section].dob)"

    print(dob)
    var dobSplit = dob.split(separator:"-")
    print (dobSplit)
    var mont = dobSplit[1]
    var dat = dobSplit[2]
    print(dat,mont)


    var monthArray = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
    print(monthArray)
    print(monthArray[Int(mont)!-1])

    var mo = monthArray[Int(mont)!-1]

    var finalDOB = dat + " " + mo
    print(finalDOB)


 // cell.dateLbl.text = "\(arrdata[indexPath.row+1].dob)"
    // instead of that I gave like this 
     cell.dateLbl.text = finalDOB 

for all names its displaying same dates

EX: Rohit 28 Mar
Rahul 28 Mar
Sohit 28 Mar
Kuldeep 28 Mar


Solution

  • Use DateFormatter to get the required date format like,

    func getFormattedDate(from str: String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        if let date = dateFormatter.date(from: str) {
            dateFormatter.dateFormat = "dd MMM"
            return dateFormatter.string(from: date)
        }
        return nil
    }
    

    To add the formattedDate in your cell, use indexPath.row instead of indexPath.section, i.e.

    let dob = "\(arrdata[indexPath.row].dob)"
    cell.dateLbl.text = getFormattedDate(from: dob)
    

    Still if it is printing the same date in every cell of tableView, try adding the array of string dates that you're using for each cell. Also the UITableViewDataSource methods.