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;
}
}
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
}
}
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
}
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