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

时间:2016-03-02 22:33:30

标签: swift logic nsdate

我有一个日期说2 March 2016存储为NSUserDefaults我希望每次新月即将到来时在TableView中添加一个新行,那么我应该怎样做才能完成此任务,IMO比较存储的日期和当前日期以及是否 在Curent Date中,新的一个月即将在未来7天内出现,然后添加 我不知道从哪里开始,如果新的月份即将来临,任何人都可以给我一些提示,以便查看当前日期的下一个7天

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

请参阅示例以便更好地理解:

storedDate = 2 March 2016
currentDate = 26 March 2016

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

1 个答案:

答案 0 :(得分:1)

您可以向NSDate添加扩展,然后执行各种日/月添加

您可以使用此方法将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的日期帮助页面。他们都在Obj-c中,但可以很容易地转换为swift。当我需要帮助进行日期数学时,我仍然会参考它