Re: NSDate/NSDateFormatter question
Re: NSDate/NSDateFormatter question
- Subject: Re: NSDate/NSDateFormatter question
- From: Roland King <email@hidden>
- Date: Sun, 25 Mar 2012 11:58:47 +0800
On Mar 25, 2012, at 11:14 AM, Donald Hall wrote:
> Can anyone explain what is going on here:
>
> NSDate *now = [NSDate date];
> NSLog(@"now is %@", now);
>
> NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
> [dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; // this is MDT for me
> [dateFormatter setDateFormat:@"h:mm a"];
> NSString *newDateString = [dateFormatter stringFromDate:now];
> NSLog(@"stringFromDate=%@", newDateString);
>
> NSDate *newDateFromString = [dateFormatter dateFromString:newDateString];
> NSLog(@"new date from string=%@", newDateFromString);
>
> newDateString = [dateFormatter stringFromDate:now];
> NSLog(@"2nd stringFromDate=%@", newDateString);
>
> result:
>
> 2012-03-24 20:57:18.976 calendardatetest[77052:707] now is 2012-03-25 02:57:18 +0000
> 2012-03-24 20:57:18.977 calendardatetest[77052:707] stringFromDate=8:57 PM
> 2012-03-24 20:57:18.978 calendardatetest[77052:707] new date from string=1970-01-02 03:57:00 +0000
> 2012-03-24 20:57:18.979 calendardatetest[77052:707] 2nd stringFromDate=8:57 PM
>
> "now" is what I expected as the test was done at 8:57 PM local time, which being MDT is 6 hours behind GMT
>
> When I go in reverse using just the time string, the time for the new date object seems to ignore Daylight Saving Time - it gives 3:57 on the next day instead of 2:57.However, if I create a new date string from this I get the correct local time again, with DST taken into account. (I don't care about the y-m-d part of the date object in my application.)
>
You need to care about the YMD portion of the date as that determines whether you are MST or MDT. So yes, today, 8.57pm local is 2.57pm UTC as your code shows, but on 1 Jan 1970, 8.57pm local was 3,57am the next day.
And your timezone isn't really MDT I think, that timezone you get from [ NSTimeZone localTimeZone ] is a complicated object which represents a place only, not a part of the year. If you check the name property on it, you should get something like America/Denver, America/Boise, America/Shiprock or America/Phoenix. So it cares what date you give it and it's doing the correct thing.
_______________________________________________
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