开发者

How to output NSDate with defaulttimezone?

How can I output the current date and time with the defaulttimezone? When I use following code I always get the time in GMT. Is it possible t开发者_如何学Goo convert NSDate to the defaulttimezone? I can’t use the NSDateFormatter because I need an NSDate Object with the correct time.

NSDate *date = [NSDate date];
NSLog(@"Time: %@", date);

Output: 2010-09-26 12:07:12 TimeTest[2641:207] Time: 2010-09-26 12:07:12 GMT

Update: When I have to return an NSDate object with the right time, how can I use NSDateFormatter with setTimeZone?

 NSDate* date = [NSDate date];

 NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
 [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
 NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"MESZ"];
 [formatter setTimeZone:tz];

 NSString *datestr = [formatter stringFromDate:date];
 NSLog(@"%@", datestr);

 NSDate *datenew = [formatter dateFromString:str];
 NSLog(@"%@", datenew);

The first NSLog outputs the correct time but when I want to make an NSDate object with the correct time I get the wrong time again.


I can’t use the NSDateFormatter because I need an NSDate Object with the correct time.

That doesn't make any sense. NSDate represents a single point in time. It does not know nor care about time zones. For example, Today, 12:00 GMT and Today, 06:00 –0600 would be represented by one and the same NSDate object.

To display a date in a specific timezone, use NSDateFormatter, specifically its setTimeZone: method.


Sometimes you DO want to have the current time ([NSDate date], but have it converted to your time zone, and not just formatted that way for the user, but to do calculations with it. I came up with this simple solution:

double timeDifference = [[NSTimeZone systemTimeZone] secondsFromGMT];
double now = [[NSDate date] timeIntervalSince1970] + timeDifference;

It is useful for getting the current timeInterval, in my time zone. In my case, the dates were all very flexible and dynamic, and not linked to any calender. I was working with times relative to a start time.

Difficult to explain. Anyway, maybe some people with my issue, who ended up in this post, now have their answer too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜