Mc.Lover Mc.Lover - 1 year ago 57
iOS Question

How to calculate current date and show it to each UITableViewCell

my table view has 365 cells (number of days in year) now I need to show each date in each single cell for example if today is 2 Jul , the next cell should be 3 then 4 ,5 ,6 and ... .

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

return 1

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return 365

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

// ... setup custom cell = dayIndexPath()
return cell

now I am trying to create a method which gets current date :

func dayIndexPath(indexPath:NSIndexPath) -> String {

let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()

var convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateFormat = "d"
convertedDate = dateFormatter.stringFromDate(currentDate)

let dayArray = [convertedDate]

let row:Int = indexPath.row
return dayArray[row % dayArray.count]


The problem is above function only shows today date in each cells. I think I need to pass
and then calculate them to guess what is the next day. But I am not sure how to do so ! I would be grateful if you help me out.

Answer Source

Basically you want to add a day by the next indexPath.row days, which will be 365 starting from today (indexPath.row = 0)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)

    let todayDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "d"
    let calculatedDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.Day, value: indexPath.row, toDate: todayDate, options: NSCalendarOptions.init(rawValue: 0))
    let calculatedDayString = dateFormatter.stringFromDate(calculatedDate!)

    cell.textLabel?.text = calculatedDayString
    return cell
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download