What is the best way to know if a date is in the same week (or year or month) as another, preferably with an extension, and solely using Swift?
As an example, in Objective-C I have
- (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]);
}
Please don't propose solutions bridging Date
to NSDate
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…