每个月在 tableView 中添加一个新行

add a new row in tableView every single month

我有一个日期说 2 March 2016 存储为 NSUserDefaults 并且我想在每次新的月份即将到来时在 TableView 中添加一个新行,所以我应该怎么做才能完成这个, IMO 比较存储的日期和当前日期,如果 在 Current Date 下一个新的月份即将到来 7 天然后添加 排到 table 但我不知道从哪里开始,任何人都可以给我一些提示来检查当前日期的未来 7 天是否即将到来

如果我的方法不够好,请指正我,我会非常感激并对我有所帮助

请查看示例以便更好地理解:

storedDate = 2 March 2016
currentDate = 26 March 2016

if CurrentDate + 1 Week == newMonth {
 //add the Row into TableView
 } 

您可以向 NSDate 添加扩展,然后进行各种 day/month 添加

您可以使用此方法将当前日期增加 7 天...

func dateByAddingDays(daysToAdd: Int)-> NSDate {
    let dateComponents = NSDateComponents()
    dateComponents.day = daysToAdd
    let newDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: self, options: .MatchFirst)
    return newDate!
}

此方法将月份添加到当前日期

func dateByAddingMonths(monthsToAdd: Int)-> NSDate {
    let dateComponents = NSDateComponents()
    dateComponents.month = monthsToAdd
    let newDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: self, options: .MatchFirst)
    return newDate!
}

然后您需要检查您创建的日期,看看它是否与存储的月份不同..

 func compareMonths(newDate:NSDate)-> Bool {
    let today = NSDate()
    let todayPlusSeven = today.dateByAddingDays(7)
    return todayPlusSeven.isNextMonth(storedDate)
 }

使用此方法检查2个日期的月份是否相同

func isNextMonth(storedDate: NSDate)-> Bool {
    return isSameMonthAsDate(storedDate.dateByAddingMonth(1))
}

func isSameMonthAsDate(compareDate: NSDate)-> Bool {
    let comp1 = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: self)
    let comp2 = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: compareDate)
    return ((comp1.month == comp2.month) && (comp1.year == comp2.year))
}

这是一个老歌,但仍然是好东西,这是来自 Erica Sadun 的 github 页面 here 的 Date helpers 页面 here 它们都在 Obj-c 中,但可以很容易地转换为 swift .当我需要帮助做日期数学时,我仍然会参考它