Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

iphone - NSDate independent of timezone?

I have an app that displays a timetable of certain ferry trips.

If I travel to a different timezone - say 4 hours behind, a 10am ferry trip now shows up as 6am?

I know this has got to do with how dates are treated based on their timezones, but I can't work out how to change that behaviour.

At the moment here's how I am getting the date and displaying it on a UILabel:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
[self.departureTime setText:[dateFormatter stringFromDate:[self.route objectForKey:@"departureTime"]]];
[self.arrivalTime setText:[dateFormatter stringFromDate:[self.route objectForKey:@"arrivalTime"]]];
[dateFormatter release];

Thanks in advance for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to store the timezone that the ferry ride is taking place in and format it for that timezone.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"]; 

NSDate *now = [NSDate date];   
NSLog(@"now:%@", [dateFormatter stringFromDate:now]);

NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)];     
[dateFormatter setTimeZone:timeZone];
NSLog(@"adjusted for timezone: %@", [dateFormatter stringFromDate:now]);

Outputs:

2011-10-10 20:42:23.781 Craplet[2926:707] now:20:42
2011-10-10 20:42:23.782 Craplet[2926:707] adjusted for timezone: 16:42

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...