Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if NSDate is in current week?

How to check if NSDate falls in current week of the year? I tried below but last week's date is also falling inside "Date is in this week" condition.

- (NSInteger)thisW:(NSDate *)date
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *todaysComponents =
    [gregorian components:NSWeekCalendarUnit fromDate:[NSDate date]];

    NSUInteger todaysWeek = [todaysComponents weekday];


    NSDateComponents *otherComponents =
    [gregorian components:NSWeekCalendarUnit fromDate:date];

    NSUInteger datesWeek = [otherComponents weekday];
    NSLog(@"Date %@",date);
    if(todaysWeek==datesWeek){
        //NSLog(@"Date is in this week");
        return 1;
    }else if(todaysWeek+1==datesWeek){
        //NSLog(@"Date is in next week");
        return 2;
    } else {
        return 0;
    }

}
like image 344
Deepak Thakur Avatar asked Feb 07 '23 08:02

Deepak Thakur


2 Answers

What about this short extension in Swift 4?

extension Calendar {
    func isDayInCurrentWeek(date: Date) -> Bool? {
        let currentComponents = Calendar.current.dateComponents([.weekOfYear], from: Date())
        let dateComponents = Calendar.current.dateComponents([.weekOfYear], from: date)
        guard let currentWeekOfYear = currentComponents.weekOfYear, let dateWeekOfYear = dateComponents.weekOfYear else { return nil }
        return currentWeekOfYear == dateWeekOfYear
    }
}
like image 150
j3141592653589793238 Avatar answered Feb 13 '23 06:02

j3141592653589793238


A solution using the method rangeOfUnit:startDate:interval:forDate of NSCalendar to calculate the start date and the interval of the current week

- (BOOL)isInCurrentWeek:(NSDate *)date
{
  NSDate *startDate = nil;
  NSTimeInterval interval = 0.0;
  NSCalendar *calendar = [NSCalendar currentCalendar];
  // calendar.firstWeekday = 1; set the index of the first weekday if necessary
  [calendar rangeOfUnit:NSWeekOfYearCalendarUnit startDate: &startDate interval: &interval forDate: [NSDate date]];
  NSDate *endDate = [calendar dateByAddingUnit:NSSecondCalendarUnit value: (NSInteger)interval toDate: startDate options:NSCalendarMatchNextTime];
  return [date compare:startDate] == NSOrderedDescending && [date compare:endDate] == NSOrderedAscending;
}

or in Swift

func isDateInCurrentWeek(_ date : Date) -> Bool
{
    var startDate = Date()
    var interval : TimeInterval = 0.0
    let calendar = Calendar.current
    // calendar.firstWeekday = 1 set the index of the first weekday if necessary
    calendar.dateInterval(of: .weekOfYear, start: &startDate, interval: &interval, for: Date())
    let endDate = calendar.date(byAdding:.second, value: Int(interval), to: startDate)!
    return date >= startDate && date < endDate
}
like image 37
vadian Avatar answered Feb 13 '23 07:02

vadian