知道某个日期是在同一周(或年份或月份)中的最佳方式是什么,最好是使用扩展,并且只使用
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]); }
解决方法
您可以使用日历方法isDate(equalTo:granularity :)来检查它如下:
extension Date { func isInSameWeek(date: Date) -> Bool { return Calendar.current.isDate(self,equalTo: date,toGranularity: .weekOfYear) } func isInSameMonth(date: Date) -> Bool { return Calendar.current.isDate(self,toGranularity: .month) } func isInSameYear(date: Date) -> Bool { return Calendar.current.isDate(self,toGranularity: .year) } func isInSameDay(date: Date) -> Bool { return Calendar.current.isDate(self,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() } }