I have created an NSDate category that would give me a “last sunday” date.
+(NSDate *)sunday{
// I need 2 dates yesterday and today
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSLog(@"Current date: %@", now);
NSDateComponents *components = [gregorian components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit ) fromDate:now];
[components setWeekday:1]; //Monday
[components setHour:0]; //8a.m.
[components setMinute:0];
[components setSecond:0];
NSLog(@"Sunday: %@", [gregorian dateFromComponents:components]);
return [gregorian dateFromComponents:components];
}
This give me a couple different dates:
IOS 4.2
Sunday: 0001-08-28 05:50:36 +0000
IOS 4.1
Sunday: 0001-09-04 05:50:36 GMT
Notice
That IOS 4.1 give me a future date, whereas IOS 4.2 gives me a previous date, which is what I want.
I understand that the year is 0001 is shown, but the year is not used.
I have not yet found where others are having this same issue, so perhaps I’m doing something wrong. But, I’m not sure what that is. Has anyone seen this before?
EDIT
Here is my working code:
+(NSDate *)sunday{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [gregorian components:(NSWeekCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit ) fromDate:now];
[components setWeekday:[gregorian firstWeekday]]; //Sunday
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
return [gregorian dateFromComponents:components];
}
Thanks!!
You should probably reconsider your assertion that the year is not used. Sure, 2011-09-04 and (by the Julian calendar used by NSGregorianCalendar for dates before 1582-10-15) 0001-09-04 are both Sundays so it seems like it doesn’t matter. But next year it won’t match up.
Your problem with the differing results on the two devices is most likely that your devices are set to different regions, with different rules about which day is the first day of the week or which week is the first of the year. You can check the
firstWeekdayproperty on your NSCalendar object to determine the first, andminimumDaysInFirstWeekwill help with the latter.