如果您使用的是iOS 10+或MacOS 10.12+,则可以使用这两种Calendar
方法来正确执行此操作。
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)
这是一个如何在Swift 3中使用这些方法的示例,以及我所在时区的游乐场输出。
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
奖励:您可以使用DateInterval
来测试日期是否在该范围内。从上面继续:
thisWeekInterval!.contains(now)
lastMonthInterval!.contains(now)