FROM : Nick Zitzmann
DATE : Mon Feb 25 20:57:35 2008
On Feb 25, 2008, at 12:27 PM, Randall Meadows wrote:
> Given a specific NSDate, I need to be able to find, say, the Sunday
> before that date, or the Saturday after that date. I was hoping to
> be able to use +dateWithNaturalLanguage with something like "Sunday
> before [myDate description]", but that just returns myDate.
>
> I know I can brute-force it, by figuring out the myDate's day, then
> walking backward and/or forward, but is there an easier way? One
> more tried and true, less error-prone, that's calendar-savvy (not
> that I'm going to need to go as far back as Oct 1582...)?
You can do this with NSCalendar, doing something like this: (warning,
written in Mail, untested, use at your own risk, etc.)
NSCalendar *cal; // initialize this
NSDate *date; // initialize this
NSDate *dateLastSunday;
NSInteger weekday;
NSDateComponents *addComponents = [[[NSDateComponents alloc] init]
autorelease];
weekday = [[cal components:NSWeekdayCalendarUnit fromDate:date]
weekday];
if (weekday == 1) // Sunday
[addDateComponents setDay:-7];
else // Monday-Saturday
[addDateComponents setDay:(weekday-1)*-1];
dateLastSunday = [cal dateByAddingComponents:addDateComponents
toDate:date options:0];
Nick Zitzmann
<http://www.chronosnet.com/>
DATE : Mon Feb 25 20:57:35 2008
On Feb 25, 2008, at 12:27 PM, Randall Meadows wrote:
> Given a specific NSDate, I need to be able to find, say, the Sunday
> before that date, or the Saturday after that date. I was hoping to
> be able to use +dateWithNaturalLanguage with something like "Sunday
> before [myDate description]", but that just returns myDate.
>
> I know I can brute-force it, by figuring out the myDate's day, then
> walking backward and/or forward, but is there an easier way? One
> more tried and true, less error-prone, that's calendar-savvy (not
> that I'm going to need to go as far back as Oct 1582...)?
You can do this with NSCalendar, doing something like this: (warning,
written in Mail, untested, use at your own risk, etc.)
NSCalendar *cal; // initialize this
NSDate *date; // initialize this
NSDate *dateLastSunday;
NSInteger weekday;
NSDateComponents *addComponents = [[[NSDateComponents alloc] init]
autorelease];
weekday = [[cal components:NSWeekdayCalendarUnit fromDate:date]
weekday];
if (weekday == 1) // Sunday
[addDateComponents setDay:-7];
else // Monday-Saturday
[addDateComponents setDay:(weekday-1)*-1];
dateLastSunday = [cal dateByAddingComponents:addDateComponents
toDate:date options:0];
Nick Zitzmann
<http://www.chronosnet.com/>
| Related mails | Author | Date |
|---|---|---|
| Randall Meadows | Feb 25, 20:27 | |
| Nir Soffer | Feb 25, 20:39 | |
| Nick Zitzmann | Feb 25, 20:57 | |
| Deborah Goldsmith | Feb 26, 00:49 | |
| Paul Bruneau | Feb 26, 14:45 | |
| Deborah Goldsmith | Feb 26, 21:39 |






Cocoa mail archive

