I created a method to calculate the first and last day of week, by adding a time interval of one day (86,400) to a date, multiplied by the required number of days.
A colleague commented "adding multiples of 86,400 is never the answer". Why is this so?
Here's the category method that I created, how can I improve this?
- (NSDate*)firstDayOfWeek
{
return [self dateWithDaysAddedGivenDayOfWeek:@{
@1 : @-6,
@2 : @0,
@3 : @-1,
@4 : @-2,
@5 : @-3,
@6 : @-4,
@7 : @-5
}];
}
- (NSDate*)lastDayOfWeek
{
return [self dateWithDaysAddedGivenDayOfWeek:@{
@1 : @0,
@2 : @6,
@3 : @5,
@4 : @4,
@5 : @3,
@6 : @2,
@7 : @1
}];
}
- (NSDate*)dateWithDaysAddedGivenDayOfWeek:(NSDictionary*)daysToAddGivenDay
{
NSDateComponents* components = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit fromDate:self];
NSInteger daysToAdd = [[daysToAddGivenDay objectForKey:@([components weekday])] integerValue];
return [self dateByAddingTimeInterval:daysToAdd * 60 * 60 * 24];
}
Do I need to use a different time interval for the day? (eg 23 hours, 56 minutes, 4.1 seconds)