Question

I'm creating a weekly calendar view, and part of that is calculating the first day of the displayed week. I also want the saved date to have the time of the very first second, so I'm trying to ensure that hh:mm:ss for the date are all 00:00:00.

I have the following code, which works fine in most cases but gives seemingly random results when the dates are around the beginning or end of a year.

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *comps = [gregorian components:unitFlags fromDate:self.selectedDate];
NSDateComponents *addcomps = [[NSDateComponents alloc] init];
[addcomps setDay:1-[comps weekday]];

NSDate *fixedDate = [appDelegate.gregorian dateByAddingComponents:addcomps toDate:self.selectedDate options:0];
////FIXED DATE IS NOW FIRST DAY OF DISPLAYED WEEK

comps = [appDelegate.gregorian components:unitFlags fromDate:fixedDate]; ///fixedDate = 2010-01-03 02:51:25 -0600
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
self.savedBeginningDate = [appDelegate.gregorian dateFromComponents:comps]; ///self.savedBeginningDate = 2011-01-09 00:00:00 -0600

Somehow setting the hh:mm:ss to 00:00:00 changes the date from January 3, 2010 to January 11, 2009.

I've added the results of the dateFromComponents as comments on those lines. This odd behavior only seems to happen when around the year marks and doesn't happen for any other week that I've seen.

Thanks for any help!

Was it helpful?

Solution

I've figured this out: I had to take out the NSWeekCalendarUnit from the unitFlags. No clue why, but for some reason with that in there the dates were calculating incorrectly!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top