如何将时间转换为iPhone设备的时区?

我在EST时区有一段时间,它使用mysql服务器上的NOW()函数完成。 由于我的服务器位于EST,所以存储的时间是EST。 当我从iPhone上的应用程序检索到它时,我需要将其显示在用户的正确时区中。 我怎么做?

我认为这取决于你的意思是什么 – 如果你的意思是美国东海岸,那么一般来说,这比UTC的时间晚了5个小时(但是不考虑夏令时),这应该会给你04:00东部时间。 尽量避免使用缩写,因为它们是模棱两可的,例如,EST是美国/底特律和澳大利亚/悉尼的缩写。 使用NSTimeZone initWithName将会给出更精确的结果。

Chronos时区库提供了一个很好的可读的XML时区数据库,这有助于理解时区是如何工作的(这一切都相当混乱和可改变)。

//您可以使用下面的函数将date转换为您希望的时区

+ (NSDate *) convertDate:(NSDate *) date toTimeZone:(NSString *) timeZoneAbbreviation { NSTimeZone *systemZone = [NSTimeZone systemTimeZone]; NSTimeZone *zoneUTC = [NSTimeZone timeZoneWithAbbreviation:timeZoneAbbreviation]; NSTimeInterval s = [zoneUTC secondsFromGMT]; NSTimeZone *myZone = [NSTimeZone timeZoneWithAbbreviation:[systemZone abbreviationForDate:date]]; NSTimeInterval p = [myZone secondsFromGMT]; NSTimeInterval i = sp; NSDate *d = [NSDate dateWithTimeInterval:i sinceDate:date]; return d; } //Test case **note** cgUtil is the class this method is written thus change it accordingly __block NSDate *now = [NSDate date]; NSLog(@"Current time:%@", now); [[[NSTimeZone abbreviationDictionary] allKeys] enumerateObjectsUsingBlock:^(NSString * abb, NSUInteger idx, BOOL *stop) { NSLog(@"Time zone abb:%@:Time:%@",abb,[cgUtil convertDate:now toTimeZone:abb]); }];