Skip navigation.
 
mlRe: NSDateComponents question
FROM : mmalc crawford
DATE : Tue Jul 01 20:37:12 2008

On Jul 1, 2008, at 10:44 AM, Chris Kane wrote:

>> My apologies; I did do some testing and found that the resultant 
>> date was always correct.
>> Could you elaborate on what circumstances this might not be correct?

> Did you try starting with a starting date of  Jan 1, 2009?  The 
> Weekday would be 5, the Day 1.
>

Rats, no; I tried the dates at the beginning of 2008, 2003, and 1999...

> The previous Sunday is December 28, 2008.
>

... although, hmm, yes, that's the result I get(*).  Nevertheless...

> Passing a Year, Month, Day of (2009, 1, -3)  (-3 == 1 - (5 - 1) in 
> your original computation) is passing an out-of-bounds value with 
> dateWithComponents:, with who-knows-what effect.  It might be well-
> defined, it might not be.  The result might change between OS 
> releases.  In other words, it seems a bit ambiguous, so best to just 
> avoid it.
>

... point taken.  I'll update the documentation accordingly.

mmalc


(*)
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:2009];
    [components setMonth:1];
    [components setDay:1];
    NSDate *testDate = [gregorian dateFromComponents:comps];
    [components release];

    NSDateComponents *components = [gregorian 
components:NSWeekdayCalendarUnit | NSYearCalendarUnit | 
NSMonthCalendarUnit | NSDayCalendarUnit fromDate:testDate];

    NSLog(@"day: %d, weekDay: %d, delta: %d", [components day], 
[components weekday], [components day] - [components weekday]);
    // day: 1, weekDay: 5, delta: -4

    [components setDay:([components day] - ([components weekday] - 
1))];
    [components setWeekday:NSUndefinedDateComponent];

    NSDate *beginningOfWeek = [gregorian 
dateFromComponents:components];
    NSLog(@"beginningOfWeek: %@", beginningOfWeek);
    // beginningOfWeek: 2008-12-28 00:00:00 -0800

Related mailsAuthorDate
mlNSDateComponents question Jason Wiggins Jun 30, 18:45
mlRe: NSDateComponents question mmalc crawford Jun 30, 19:02
mlRe: NSDateComponents question Jason Wiggins Jun 30, 19:27
mlRe: NSDateComponents question mmalc crawford Jul 1, 10:08
mlRe: NSDateComponents question Jason Wiggins Jul 1, 12:41
mlRe: NSDateComponents question Christopher Kane Jul 1, 18:10
mlRe: NSDateComponents question mmalc crawford Jul 1, 18:26
mlRe: NSDateComponents question Chris Kane Jul 1, 19:44
mlRe: NSDateComponents question mmalc crawford Jul 1, 20:37
mlRe: NSDateComponents question Jason Wiggins Jul 2, 02:20
mlRe: NSDateComponents question mmalc crawford Jul 2, 02:41
mlRe: NSDateComponents question Jason Wiggins Jul 2, 03:20
mlRe: NSDateComponents question Jason Wiggins Jul 2, 03:48