Search code examples
iosswiftdatedateformatter

Make sure returned dates are within seven days of current date


Currently I am using these group of functions to filter date objects that are used inside my app.

func isInSameWeek(date: Date) -> Bool {
    return Calendar.current.isDate(self, equalTo: date, toGranularity: .weekOfYear)
}
func isInSameMonth(date: Date) -> Bool {
    return Calendar.current.isDate(self, equalTo: date, toGranularity: .month)
}
func isInSameYear(date: Date) -> Bool {
    return Calendar.current.isDate(self, equalTo: date, toGranularity: .year)
}
func isInSameDay(date: Date) -> Bool {
    return Calendar.current.isDate(self, equalTo: date, toGranularity: .day)
}
var isInThisWeek: Bool {
    return isInSameWeek(date: Date())
}
var isInToday: Bool {
    return Calendar.current.isDateInToday(self)
}
var isInTheFuture: Bool {
    return Date() < self
}
var isInThePast: Bool {
    return self < Date()
}

They are working fine but the only issue is that I want to return date objects that are within 7 days of the current day. So if a date object occurs on the Feb 11th than it should be returned as well. Currently what I have won't return anything unless it is literally in the same calendar week.


Solution

  • This is a solution getting the end date with the nextDate(after:matching:matchingPolicy:) API of Calendar

    extension Date {
        func isInSevenDays() -> Bool {
            let now = Date()
            let calendar = Calendar.current
            let weekday = calendar.dateComponents([.weekday], from: now)
            let startDate = calendar.startOfDay(for: now)
            let nextWeekday = calendar.nextDate(after: now, matching: weekday, matchingPolicy: .nextTime)!
            let endDate = calendar.date(byAdding: .day, value: 1, to: nextWeekday)!
            return self >= startDate && self < endDate
        }
    }