MySQL 如何将时间转换为 iPhone 设备的时区?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1081647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert time to the time zone of the iPhone device?
提问by erotsppa
I have a time in EST timezone, it is done using the NOW() function on the mysql server. Because my server is located in EST, the time stored is in EST. When I retrieve it from my app on the iPhone, I need to display it in the correct time zone of the user. How do I do that?
我在 EST 时区有一段时间,它是使用 mysql 服务器上的 NOW() 函数完成的。因为我的服务器在EST,所以存储的时间是在EST。当我从 iPhone 上的应用程序中检索它时,我需要在用户的正确时区中显示它。我怎么做?
回答by StephenT
I think it depends on what you mean by EST - if you mean East Coast US, then in general, that is 5 hours behind UTC (but not accounting for daylight saving), which should give you 04:00 EST. Try to avoid using abbreviations where possible, as they are ambiguous, e.g. EST is the abbreviation for both America/Detroit and Australia/Sydney. Using NSTimeZone initWithName will give more precise results.
我认为这取决于您所说的 EST 是什么意思——如果您指的是美国东海岸,那么一般来说,这比 UTC 晚 5 小时(但不考虑夏令时),这应该是美国东部时间 04:00。尽量避免使用缩写,因为它们会引起歧义,例如 EST 是 America/Detroit 和 Australia/Sydney 的缩写。使用 NSTimeZone initWithName 将提供更精确的结果。
The Chronos Time Zone Repositoryprovides a nicely readable XML timezone database that really helps in understanding how time zones work (it's all rather messy and changeable).
该Chronos的时区库提供了一个很好的可读XML区数据库,真正有助于了解时区的工作(这一切都相当混乱和多变的)如何。
回答by Chamira Fernando
//You can use the below function to convert date to a time zone you wish
//您可以使用以下函数将日期转换为您希望的时区
+ (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 = s-p;
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]);
}];