iPhone - NSDate formatting : strange values for times and timezones
I tested those calls :
NSLog(@"%@", [NSDate date]);
NSLog(@"%@", [NSDate convertToUTC:[NSDate date]]);
NSLog(@"%@", [[NSDate date] stringValueWithFormat:@"yyyyMMddHHmmss"]);
NSLog(@"%@", [[NSDate convertToUTC:[NSDate date]] stringValueWithFormat:@"yyyyMMddHHmmss"]);
+ (NSDate*) convertToUTC:(NSDate*)sourceDate {
[NSTimeZone resetSystemTimeZone];
NSTimeZone* currentTimeZone = [NSTimeZone localTime开发者_运维技巧Zone];
NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:sourceDate];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval gmtInterval = gmtOffset - currentGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:sourceDate] autorelease];
return destinationDate;
}
- (NSString*) stringValueWithFormat:(NSString*)formatRetour {
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:formatRetour];
return [dateFormatter stringFromDate:self];
}
They give me :
2011-08-17 13:03:58 +0000
2011-08-17 11:03:58 +0000
20110817150358
20110817130358
On my phone, all configured to France/French, it's now : 15:03:58.
I don't understand the conversions that are done here.
1 gives me the real time at GMT
2 gives me something I don't understand... 3 gives the real time on the phone 4 gives the real time at GMTI'm lost... From where does 2 comes ? How does those calls work ?
I mean, [NSDate date] gives 13:03 whith a +0000 timezone. Why formatting it shows 15:03 ? Why 1 and 2 show a +0000 timezone, but different times ?Could you guide me through this ?
NSLog
will always print the description of the date object with a +0000 timezone.
When you use a NSDateFormatter
to get a string from your date, it will use the timezone of your phone. With "yyyyMMddHHmmssZZZ"
you would have got 20110817150358+0200
.
It's the same thing for the date you convert to UTC: you get 11:03 for GMT+0 (NSLog) which is the same as 13:03+0200 (using NSDateFormatter).
Yet convertToUTC:
is buggy since the value should be 13:03+0000.
NSDate to NSDate conversion methods don't make sense. NSDate
holds an absolute time and does not care about timezones. You only have to take timezones into account when doing NSString from/to NSDate conversions.
That's why when you "convertToUTC" 15:03+0200 you get 13:03+0200 which is the same as 11:03+0000.
A method like - (NSString *)UTCRepresentation
would make sense though.
Don't be confused by the NSLog
output. NSLog also needs a formatter to display [NSDate date]
correctly. When you factor that in it should all make sense.
精彩评论