开发者

Timezone convert result error

开发者 https://www.devze.com 2023-01-19 01:49 出处:网络
CCT is UTC + 6:30 and SGT is UTC + 8:00. However result is wrong NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

CCT is UTC + 6:30 and SGT is UTC + 8:00. However result is wrong

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM dd, yyyy h:mm"];


// The date in your source timezone (eg. EST)
NSDate* sourceDate = [NSDate date];


 NSLog([formatter stringFromDate:sourceDate]);

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"SGT"];
//NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"CCT"];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];


NSLog([formatter stringFromDate:destinationDate]);

Result is look like that

2010-10-06 14:45:41.143 TimeZone[4805:207] October 06, 2010

2:45 2010-10-06 14:45:41.1开发者_运维技巧44 TimeZone[4805:207] October 06, 2010 6:45

I change to

NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Rangoon"];

it's working fine. Why not work with timeZoneWithAbbreviation


because "CCT" is not valid as abbreviation. You could have checked that like this:

NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Rangoon"];
NSLog(@"%@", [destinationTimeZone name]);
NSLog(@"%@", [destinationTimeZone abbreviation]);

this prints out:

2010-10-06 09:10:59.846 MyTest[39159:207] Asia/Rangoon
2010-10-06 09:10:59.892 MyTest[39159:207] GMT+06:30

see the discussion in the documentation for timeZoneWithAbbreviation:

In general, you are discouraged from using abbreviations except for unique instances such as “UTC” or “GMT”. Time Zone abbreviations are not standardized and so a given abbreviation may have multiple meanings—for example, “EST” refers to Eastern Time in both the United States and Australia

btw, you can get a NSDictionary with valid abbreviations with [NSTimeZone abbreviationDictionary]

0

精彩评论

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