Re: NSCalendar date calculation anomaly
Re: NSCalendar date calculation anomaly
- Subject: Re: NSCalendar date calculation anomaly
- From: glenn andreas <email@hidden>
- Date: Wed, 28 Apr 2010 09:11:59 -0500
On Apr 27, 2010, at 10:45 PM, Scott Ribe wrote:
> I have an int representing the number of days since 1/1/2001, and wish to get an NSDate representing that date in the system's local time zone:
>
> NSDateComponents *dc = [[[NSDateComponents alloc] init] autorelease];
> [dc setDay: numdays];
> NSDate * cd = [[NSCalendar currentCalendar] dateByAddingComponents: dc toDate: [NSDate dateWithString: @"2001-01-01"] options: 0];
> NSLog( @"date 1: %@", [cd description] );
> [dc setDay: 0];
> [dc setSecond: -[[NSTimeZone systemTimeZone] secondsFromGMTForDate: cd]];
> cd = [[NSCalendar currentCalendar] dateByAddingComponents: dc toDate: cd options: 0];
> NSLog( @"date 2: %@", [cd description] );
>
> If for example numdays is the number of days from 1/1/2001 to 5/4/2010, then the output is this:
>
> 2010-04-27 21:33:55.803 PedCard[95387:a0f] date 1: 2010-05-03 17:00:00 -0600
> 2010-04-27 21:33:55.804 PedCard[95387:a0f] date 2: 2010-05-03 23:00:00 -0600
>
> And, BTW, my current time zone is MDT, so -0600 is not correct, it should be -0700. So what's going on? I would expect those dates to be:
>
> 2010-05-03 17:00:00 -0700
> 2010-05-04 00:00:00 -0700
>
MDT is -0600 so this is correct - MST is -0700. (stupid "spring forward, fall back" clock resetting...)
I find that dealing with dates and time zones it's best to consider NSDate to be just a scalar value, with a separate time zone (and optional calendar) being the "unit". It's up to the formatter used to display that (scalar) date in the desired unit.
Glenn Andreas email@hidden
The most merciful thing in the world ... is the inability of the human mind to correlate all its contents - HPL
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden