什么是最好的方式来知道某个日期是否与另一个日期在同一周(或一年或一个月),最好是带扩展名,并且 仅使用Swift ?
例如,在Objective-C中,我有
- (BOOL)isSameWeekAs:(NSDate *)date { NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self]; NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date]; return ([today weekOfYear] == [otherDay weekOfYear] && [today year] == [otherDay year] && [today era] == [otherDay era]); }
请不要提出桥Date接到的解决方案NSDate
Date
NSDate
您可以使用日历方法isDate(equalTo:granularity:)进行检查,如下所示:
isDate(equalTo:granularity:)
Xcode 11•Swift 5.1
extension Date { func isEqual(to date: Date, toGranularity component: Calendar.Component, in calendar: Calendar = .current) -> Bool { calendar.isDate(self, equalTo: date, toGranularity: component) } func isInSameYear(as date: Date) -> Bool { isEqual(to: date, toGranularity: .year) } func isInSameMonth(as date: Date) -> Bool { isEqual(to: date, toGranularity: .month) } func isInSameWeek(as date: Date) -> Bool { isEqual(to: date, toGranularity: .weekOfYear) } func isInSameDay(as date: Date) -> Bool { Calendar.current.isDate(self, inSameDayAs: date) } var isInThisYear: Bool { isInSameYear(as: Date()) } var isInThisMonth: Bool { isInSameMonth(as: Date()) } var isInThisWeek: Bool { isInSameWeek(as: Date()) } var isInYesterday: Bool { Calendar.current.isDateInYesterday(self) } var isInToday: Bool { Calendar.current.isDateInToday(self) } var isInTomorrow: Bool { Calendar.current.isDateInTomorrow(self) } var isInTheFuture: Bool { self > Date() } var isInThePast: Bool { self < Date() } }