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
let date1 = Date() let date2 = Date(). addingTimeInterval(100) if date1 == date2 { ... } else if date1 > date2 { ... } else if date1 < date2 { ... } if i want to ignore time. e.g. 2019-05-14 12:08:14 +0000 == 2019-05-14 should return true.
To subtract hours from a date in swift we need to create a date first. Once that date is created we have to subtract hours from that, though swift does not provide a way to subtract date or time, but it provides us a way to add date or date component in negative value.
let modifiedDate = Calendar. current. date(byAdding: . day, value: 1, to: today)!
You can use calendar method isDate(equalTo:granularity:)
to check it as follow:
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() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With