Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 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 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...