views:

22

answers:

1

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 to 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.

+1  A: 

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.

Ole Begemann
I tried it with NSDateFormatter but I can’t get to the right result. Please see the code above.
MikeT
You haven't understood it yet. `date` and `datenew` represent the same point in time. The time zone in which a date is displayed is just a matter of presentation and not the actual underlying data. Therefore, your question, "When I have to return an NSDate object with the right time, how can I use NSDateFormatter with setTimeZone?", doesn't make sense. You already have an `NSDate` object with the right time.
Ole Begemann
Now I understand what you mean. I’m sorry for this bad question. Thank you!
MikeT