Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a date in same week, month, year of another date in swift

Tags:

date

ios

swift

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

like image 880
Tancrede Chazallet Avatar asked Apr 27 '17 16:04

Tancrede Chazallet


People also ask

How do I compare two dates in Swift?

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.

Can you subtract dates in Swift?

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.

How do I increment a date in Swift?

let modifiedDate = Calendar. current. date(byAdding: . day, value: 1, to: today)!


1 Answers

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() } } 
like image 136
Leo Dabus Avatar answered Oct 08 '22 02:10

Leo Dabus