iosswiftnsdatenscalendar

Check if NSDate is in current week not working for specific date?


I have tried couple of ways to check if NSDate is in current week:

Method 1

func isInThisWeek(date: Date) -> Bool
{
    return Calendar.current.isDate(date, equalTo: Date(), toGranularity: .weekOfYear)
}

Method 2

func dateFallsInCurrentWeek(date: Date) -> Bool
{
    let currentWeek = Calendar.current.component(Calendar.Component.weekOfYear, from: Date())
    let datesWeek = Calendar.current.component(Calendar.Component.weekOfYear, from: date)
    return (currentWeek == datesWeek)
} 

Now here is the case where I am getting FALSE though this date is in current week.

enter image description here

I tested on: Monday, August 10, 2020 6:00:00 PM (My time zone: +5:30 GMT). So as per calendar, this date belongs to 10 Aug - 16 Aug week.

What may be wrong? In my iPad in which I am testing this, has starting day of Week is Monday as following:

enter image description here


Solution

  • All calendars would consider sunday as the first weekday. If you would like to consider monday as the start of your week you need to use iso8601 calendar.

    let date = Date(timeIntervalSince1970: 1597516200) // .description  // "2020-08-15 18:30:00 +0000"
    let tz = TimeZone(secondsFromGMT: 5*3600 + 1800)!  // GMT+0530 (fixed)
    let components = Calendar.current.dateComponents(in: tz, from: date)
    components.day      // 16
    components.weekday  // Sunday
    // Current Calendar starts on sunday so it goes from 9...15 and 16...22
    // To get the current week starting on monday you need iso8601 calendar
    let equalToDate = DateComponents(calendar: .current, timeZone: tz, year: 2020, month: 8, day: 10, hour: 18).date!
    equalToDate.description  // "2020-08-10 12:30:00 +0000"
    Calendar(identifier: .iso8601).isDate(date, equalTo: equalToDate, toGranularity: .weekOfYear)  // true