Se utilizzi iOS 10+ o MacOS 10.12+, puoi utilizzare questi due Calendar
metodi per farlo correttamente.
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
( documenti )
func dateInterval(of component: Calendar.Component, for date: Date) -> DateInterval?
( documenti )
Ecco un esempio di come utilizzare questi metodi in Swift 3, insieme all'output dei playground nel mio fuso orario.
let calendar = Calendar.current
let now = Date()
// => "Apr 28, 2017, 3:33 PM"
let yesterday = calendar.date(byAdding: .day, value: -1, to: now)
// => "Apr 29, 2017, 3:33 PM"
let yesterdayStartOfDay = calendar.startOfDay(for: yesterday!)
// => ""Apr 29, 2017, 12:00 AM"
let thisWeekInterval = calendar.dateInterval(of: .weekOfYear, for: now)
// => 2017-04-23 04:00:00 +0000 to 2017-04-30 04:00:00 +0000
let thisMonthInterval = calendar.dateInterval(of: .month, for: now)
// => 2017-04-01 04:00:00 +0000 to 2017-05-01 04:00:00 +0000
let aDateInLastWeek = calendar.date(byAdding: .weekOfYear, value: -1, to: now)
let lastWeekInterval = calendar.dateInterval(of: .weekOfYear, for: aDateInLastWeek!)
// => 2017-04-16 04:00:00 +0000 to 2017-04-23 04:00:00 +0000
let aDateInLastMonth = calendar.date(byAdding: .month, value: -1, to: now)
let lastMonthInterval = calendar.dateInterval(of: .weekOfYear, for: aDateInLastMonth!)
// => 2017-03-26 04:00:00 +0000 to 2017-04-02 04:00:00 +0000
Bonus: puoi utilizzare la DateInterval
s per verificare se una data rientra in tale intervallo. Continuando dall'alto:
thisWeekInterval!.contains(now)
lastMonthInterval!.contains(now)