2016-03-02 27 views
0

我有一個日期說2 March 2016存儲爲NSUserDefaults,我想在每個新的月份即將到來時在TableView中添加一個新的行,那麼我應該怎麼做才能完成這一點,國際海事組織比較存儲的日期和當前日期,如果在Curent日期 新的一個月即將在未來7天內,然後將 行添加到表中,但我不知道從哪裏開始,任何人都可以給我一些提示檢查當前日期的下一個7天,如果一個新的月即將到來在tableView每個月添加一個新行

,如果我的做法是不夠好,那麼請大家指正,它會被我如此讚賞,並有助於我

請看例子更好地理解:

storedDate = 2 March 2016 
currentDate = 26 March 2016 

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

回答

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) 
} 

使用這種方法來檢查,如果兩個日期的月份是相同

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)) 
} 

一個古老的,但仍然goodie,這是從埃裏卡Sadun的github頁面here日期助手頁面他們都在Obj - c但可以很容易地轉換爲快速。我仍然參考它,當我需要幫助做日期數學

+0

感謝的人,感謝您的努力:) –

+1

確保FYI我做了這從我的頭,所以它可能需要一些調整 – bolnad

相關問題