I would like to change the color of the rows in my tableview to red.. if the date (subtitle) is older than 5 days from today. I tried something like: (example with the textfield color)
// Configure the cell...
cell.textLabel?.textColor = UIColor.blueColor()
cell.detailTextLabel?.textColor = UIColor.darkGrayColor()
let item = frc.objectAtIndexPath(indexPath) as! Item
cell.textLabel?.text = item.name! + "-" + item.etage! + "-" + item.raum!
let note = item.date
cell.detailTextLabel!.text = "\(note!)"
if note == "04.04.2016 20:31:55" {
cell.detailTextLabel?.textColor = UIColor.redColor()
} else {
}
return cell
}
and it works.. but only with the exact time (minutes, seconds). How can i do this with compare only the day minus 5 days?
答案 0 :(得分:0)
您可以使用NSDate的扩展名:
extension NSDate {
func numberOfDaysRoundedUp(toDateTime : NSDate) -> Int {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.Day, fromDate: self, toDate: toDateTime, options: [])
return abs(components.day)
}
func olderThanFiveDays(toDateTime : NSDate) -> Bool {
return (numberOfDaysRoundedUp(toDateTime) > 5)
}
}
用法:
// Today (4 April 2016 - 19:16:14)
let date : NSDate = NSDate()
// 1 April 2016 - 19:16:14
let aprilFirst : NSDate = NSDate(timeIntervalSince1970: NSTimeInterval(1459538184))
// 1 March 2016 - 19:29:00
let marchFirst : NSDate = NSDate(timeIntervalSince1970: NSTimeInterval(1456860540))
print(date.numberOfDaysRoundedUp(aprilFirst)) // 3
print(date.olderThanFiveDays(aprilFirst)) // False
print(date.numberOfDaysRoundedUp(marchFirst)) // 34
print(date.olderThanFiveDays(marchFirst)) // True
这可能是一个粗略的方法,但我认为它易于理解,易于更改并满足您的需求。