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
467 views
in Technique[技术] by (71.8m points)

objective c - NSDate is 5 hours off

I run the following code:

NSDate *now = [NSDate date];

NSLog(@"now: %@", now);

and get :

2011-09-16 16:14:16.434 iSavemore[1229:7907] now: 2011-09-16 21:14:16 +0000

As you can see i'm running this at 16:14:16 (4:14 pm) but NSDate is returning 21:16:16 (9:14 pm!). Is this an Xcode4 issue or NSDate issue?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

NSDate defaults to the Universal timezone (aka GMT).

I'm guessing you're somewhere on the East Coast, 5 hours behind UTC.

Try adding this to your date formatter...

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

[dateFormatter setLocale:[NSLocale currentLocale]];

...and you should see your local time.

If you want to use a specified locale, rather than 'currentLocale', create a NSLocale for the relevant locale.

NSLocale *usLoc = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

[dateFormatter setLocale:usLoc];

...actually that's US (so possibly not Central).

More specific timezone help can be found here...

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

However, if you want to show expiry time, wouldn't you still want it in the user's currentLocale?


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

1.4m articles

1.4m replys

5 comments

57.0k users

...