Peter Burgundy
Peter Burgundy

Reputation: 81

Swift: Trying to display weekdays from date string at indexPath.row

I'm getting dates in string format and I would like to display weekdays for each dates for each row. This is the code I have so far:

//{ConvertDate = "05/04/2015";},{ConvertDate = "05/05/2015";},{ConvertDate = "05/06/2015";},{ConvertDate = "05/07/2015";} etc...

let rowData: NSDictionary = self.tableData[indexPath.row] as! NSDictionary

//convert json date string to nsdate
var dateString = rowData["ConvertDate"] as? String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
var dateFromString = dateFormatter.dateFromString(dateString!)

//convert string into weekday
var formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "EEEE"
let stringDate: String = formatter.stringFromDate(NSDate())

//my labels        
cell.dateLabel.text = rowData["ConvertDate"] as? String
cell.dayLabel.text = stringDate

I'm getting the same weekday displayed for each row

Tuesday 05/04/2015

Tuesday 05/05/2015

Tuesday 05/06/2015

Tuesday 05/07/2015

How do I get the weekday to set based on string date for that row.

Thanks in advance

Upvotes: 0

Views: 1870

Answers (3)

Nate Cook
Nate Cook

Reputation: 93296

There's another way to do this that doesn't use a formatter to get the day name. You can index on your first NSDateFormatter's weekday symbols array after getting the date's index:

let weekdayIndex = NSCalendar.currentCalendar().component(.CalendarUnitWeekday, fromDate: dateFromString!) - 1
let weekdayString = dateFormatter.weekdaySymbols[weekdayIndex]

Upvotes: 3

Matteo Piombo
Matteo Piombo

Reputation: 6726

It appears you are always taking the week day from today NSDate(). Try:

let stringDate: String = formatter.stringFromDate(dateFromString!)

Hope this helps

Upvotes: 0

Martin R
Martin R

Reputation: 540065

let stringDate: String = formatter.stringFromDate(NSDate())

gives you the weekday from the current day. It probably should be

let stringDate: String = formatter.stringFromDate(dateFromString)

to convert the date from the corresponding element from the data source array.

Upvotes: 2

Related Questions