Si está utilizando iOS 10+ o MacOS 10.12+, puede utilizar estos dos Calendar
métodos para hacerlo correctamente.
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 )
Aquí hay un ejemplo de cómo usar estos métodos en Swift 3, junto con la salida de parques infantiles en mi zona horaria.
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
Bonificación: puede usar DateInterval
s para probar si una fecha cae en ese rango. Continuando desde arriba:
thisWeekInterval!.contains(now)
lastMonthInterval!.contains(now)