Jacksonkr Jacksonkr - 10 months ago 48
iOS Question

dynamically create date for previous sunday at 12:00 AM

I'm struggling to figure out how to dynamically create a date object for the most previous sunday at 12:00 AM

I was thinking I could get today's date and then subtract the current day of the week + 1 at which point I could just subtract the time of the day do get down to 12AM.

so far I have the current day of the week:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];

at which point I can get today's date and subtract the difference of
* seconds in a day. However, how can I get today's time in seconds ??


No need to manually calculate seconds (which is dangerous anyway because of daylight saving etc.). The following should do exactly what you want:

NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]]; // force US locale, because other countries (e.g. the rest of the world) might use different weekday numbering

NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];

[nowComponents setWeekday:1]; //Sunday
[nowComponents setHour:0]; // 12:00 AM = midnight (12:00 PM would be 12)
[nowComponents setMinute:0];
[nowComponents setSecond:0];

NSDate *previousSunday = [calendar dateFromComponents:nowComponents];