If you re using iOS 10+ or MacOS 10.12+, you can use these two Calendar
methods to do this properly.
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
(docs)
func dateInterval(of component: Calendar.Component, for date: Date) -> DateInterval?
(docs)
Here s an example of how to use these methods in Swift 3, along with the playgrounds output in my time zone.
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: You can use the DateInterval
s to test whether a date falls in that range. Continuing from above:
thisWeekInterval!.contains(now)
// => true
lastMonthInterval!.contains(now)
// => false