views:

1101

answers:

3

For PDT, I would want "-0700".

I'm getting a date in the past to determine how long ago something happened.

NSDate *then = [NSDate dateWithString:@"1976-04-01 12:34:56 -0700"]; // Note the hard-coded time zone at the end

I'll be constructing the date string elsewhere but I don't know how to access the local time zone.

I read the Apple Dates and Times Programming Topics for Cocoa as well as the NSTimeZone and NSDate Class References but it's just too hard for me to put the information together. I could really use a few lines of code just to show how it's used.

Update: While struggling with this, I was writing code using a Command Line template so I could try things quickly. I just tried my previous code on iPhone and I'm getting NSDate may not respond to '+dateWithString:' Sorry if that added to the confusion, who knew Apple would change up such a basic class.

A: 

The best way is to probably use a simple calendar formatter

NSCalendarDate * date = [NSCalendarDate calendarDate];
[date setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"PDT"]];
NSLog([date descriptionWithCalendarFormat:@"%z"]);

which will output '-0700'

or leave out the second line if you want the current time zone of the system (not sure which you were asking for)

cobbal
That isn't a formatter. That's NSCalendarDate, which is slated for deprecation.
Peter Hosey
so it is, and not even in the iPhone API it looks like
cobbal
+2  A: 

The time zone offset is dependent on the date in much of the world—those parts of it that use Daylight-Saving Time/Summer Time.

The only correct way is to generate the entire string from date and time-zone together. Use NSDateFormatter for this.

Peter Hosey
+1  A: 

Use NSDateFormatter to build NSDate from a string:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];

NSDate *formatterDate;
formatterDate = [inputFormatter dateFromString:@"1976-04-01 12:34:56 -0700"];

NSString *dateString = [inputFormatter stringFromDate:formatterDate];

NSLog(@"date:%@", dateString);

This way you get the local time from string, for example the date specified by the string:

"1976-04-01 12:34:56 -0700"

is in time zone -0700, (I'm in time zone GMT +1000) so I get:

2009-11-17 22:13:46.480 cmdline[10593:903] date:1976-04-02 05:34:56 +1000

stefanB